我怎么能重新写这个光标来计算运行总数?

时间:2017-11-22 14:03:57

标签: sql sql-server tsql sql-server-2012 cursor

所以我有一些代码每次都会丢弃并重新创建一个表,然后使用游标来计算库存量的运行总量。光标的代码如下(表格名称模糊):

DECLARE @Cust_Name nvarchar(250),
              @Cust_Postcode nvarchar(50),
              @MatchCode_Product nvarchar(50),
              --@Stock int,
              @DateKey nvarchar(8),
              @Ordered int

DECLARE StockCursor CURSOR 
  LOCAL STATIC READ_ONLY FORWARD_ONLY
FOR 
SELECT
       Cust_Name, Cust_Postcode, MatchCode_Product, DateKey
FROM
       WRK_TFT_DEPOT_STOCK
WHERE
    Cust_Name NOT LIKE {redacted}

OPEN StockCursor
FETCH NEXT FROM StockCursor INTO @Cust_Name, @Cust_Postcode, @MatchCode_Product, @DateKey

WHILE @@FETCH_STATUS = 0
BEGIN
       UPDATE
              WRK_TFT_DEPOT_STOCK
       SET

                     Ordered = isnull((
                                  SELECT
                                         sum(cast(MO.Quantity as int))
                                  FROM
                                         {redacted }DE
                                         INNER JOIN {redacted} MO
                                         ON DE.Order_No = MO.Order_No
                                  WHERE
                                         DE.Cust_Name = @Cust_Name
                                         AND
                                         DE.Cust_Postcode = @Cust_Postcode
                                         AND
                                         MatchCode_Product = @MatchCode_Product
                                         AND
                                         CAST(Year(DE.Delivery_Date) AS VARCHAR) + RIGHT('0' + CAST(Month(DE.Delivery_Date) AS VARCHAR), 2) + 
                                            RIGHT('0' + CAST(Day(DE.Delivery_Date) AS VARCHAR), 2)  <= @DateKey
                                         AND DE.Cust_Name NOT LIKE {redacted}
                                     ),0)
       WHERE
              Cust_Name = @Cust_Name
              AND
              Cust_Postcode = @Cust_Postcode
              AND
              MatchCode_Product = @MatchCode_Product
              AND
              DateKey = @DateKey 

       FETCH NEXT FROM StockCursor INTO @Cust_Name, @Cust_Postcode, @MatchCode_Product, @DateKey
END

CLOSE StockCursor
DEALLOCATE StockCursor

UPDATE
       WRK_TFT_DEPOT_STOCK
SET
       Stock = StartStock + Ordered

代码工作正常,但我的问题是运行需要很长时间,而且运行所花费的时间随着时间的推移而增加,因为我将每日数据加载到源表中。

有人能帮助我更有效地重写这个吗?从环顾四周看起来像窗口函数会有很多帮助,但我不熟悉它们。

专栏&#39; Stock&#39;是运行总额,&#39; StartStock&#39;是初始金额和“订购”#39;是我们需要添加的东西。

1 个答案:

答案 0 :(得分:1)

以前行无界限的示例:

SELECT TOP 1000 [Dato]
      ,[Department]
      ,[Amount]
      ,runningtotal = SUM(amount) over(order by dato ROWS UNBOUNDED PRECEDING)
  FROM [LegOgSpass].[dbo].[amounts]

<强>结果

enter image description here