如何避免使用while / cursor来实现相同的查询结果?

时间:2015-12-08 14:08:46

标签: sql sql-server

我想避免从下面的查询循环。现在从一个包含100000条记录的表中检索结果需要很长时间。

        @iMAX int, 
        @rowId int,
        @currCode varchar(20),
        @lastCode varchar(20),
        @amount money,
        @total money

  SET @rowId=1
  SET @iMAX=(Select count(RowId) from Table1)

WHILE(@rowId<=@iMAX)
  -- WHILE iteration
  BEGIN
        SELECT @Code=Code,@amount=Amount FROM Table1 WHERE RowId=@rowId
        if @lastCode is null or @lastCode <> @currCode
        begin 
              set @total = 0 
              set @lastCode = @currCode 
        end
        set @total = @total + @amount
        update Table1 set Balance = OpBalance + @total where RowId = @rowId

        SET @rowId=@rowId+1
  END

1 个答案:

答案 0 :(得分:0)

;WITH cte AS 
(
    SELECT *
        , total = SUM(Amount) OVER (ORDER BY RowId)
        , prevCode = LAG(Code) OVER (ORDER BY RowId)
    FROM dbo.Table1
)
UPDATE cte
SET Balance = OpBalance +
    CASE WHEN prevCode IS NULL OR prevCode != Code 
        THEN 0
        ELSE total
    END