执行存储过程需要太长时间

时间:2017-09-28 08:11:17

标签: sql

我正在尝试为我购买或销售时所拥有的所有库存物品更新库存物品。我有一个存储的工作程序可以完成工作它运行良好。但是,当我有2000个库存物品执行查询需要超过45分钟,任何想法......

CREATE PROCEDURE [dbo].[UpdateProducts]
as 
begin
DECLARE @LoopCounter INT , @MaxCode INT, 
SELECT @LoopCounter = min(ProductId) , @MaxCode = max(ProductId) 
FROM products

WHILE ( @LoopCounter IS NOT NULL
        AND  @LoopCounter <= @MaxCode)
BEGIN
   update Products set QuantityOnHand  = 

   ( 
    select (    
    (select  ISNULL (SUM (isnull (Qty,0)),0) from BILLDETAILS where Pid = @LoopCounter)          -
    (select  ISNULL (SUM (isnull (Qty,0)),0) from InvoiceDetails where Pid = @LoopCounter)       -
    (select ISNULL (SUM (isnull (Qty,0)),0) from  SalesDetails where Pid = @LoopCounter)  
    )
   where ProductId= @LoopCounter

  SELECT @LoopCounter  = min(ProductId) FROM Products
  WHERE ProductId > @LoopCounter
END  
end    
GO

3 个答案:

答案 0 :(得分:4)

我不明白为什么要使用WHILE循环来实现这一目标。您应该可以使用JOIN轻松更新所有产品:

UPDATE p
SET p.QuantityOnHand =
    (ISNULL(SUM(ISNULL(b.Qty, 0)), 0) -
     ISNULL(SUM(ISNULL(i.Qty, 0)), 0) -
     ISNULL(SUM(ISNULL(s.Qty, 0)), 0))
FROM Products p
INNER JOIN BillDetails b ON p.ProductId = b.Pid
INNER JOIN InvoiceDetails i ON p.ProductId = i.Pid
INNER JOIN SalesDetails s ON p.ProductId = s.Pid

答案 1 :(得分:1)

我知道为什么我的查询速度很慢我有一个存储上次更新日期和列的列。每行的时间。我正在使用触发器更新该列,这极大地影响了性能。

答案 2 :(得分:0)

试试这个

create PROCEDURE [dbo].[UpdateProducts]
as 
 DECLARE @productIdCursor AS int

 DECLARE
   countProduct 
 CURSOR FOR
  SELECT productId FROM Products

 OPEN   countProduct
  FETCH NEXT FROM countProduct INTO @productIdCursor
 WHILE @@fetch_status = 0
BEGIN

declare @value decimal(18,2)

set @value=(select      
    (select  ISNULL (SUM (isnull (Qty,0)),0) from BILLDETAILS where Pid = @productIdCursor)          -
    (select  ISNULL (SUM (isnull (Qty,0)),0) from InvoiceDetails where Pid = @productIdCursor)       -
    (select ISNULL (SUM (isnull (Qty,0)),0) from  SalesDetails where Pid = @productIdCursor)
    from Products where ProductId= @productIdCursor)

   update Products 
   set QuantityOnHand  =@value
   where ProductId= @productIdCursor

   print @value
    print @productIdCursor
     FETCH NEXT FROM countProduct INTO @productIdCursor

END

CLOSE countProduct
DEALLOCATE countProduct

只需更改varieble&#34; @ value&#34;的类型如果你需要