开发者

Factoring out a while loop in SQL script

开发者 https://www.devze.com 2022-12-30 13:24 出处:网络
Suppose I have a table amountInfo with columns (id, amount1, amount2, amount3) where amountX are money values and id is an int value ranging from 1 to some int under 10.

Suppose I have a table amountInfo with columns (id, amount1, amount2, amount3) where amountX are money values and id is an int value ranging from 1 to some int under 10.

Currently I have some code that approximately does this:开发者_运维问答

declare @id int, @idmax int, @amounttotal money
select @idmax = (select max(Id) from amountInfo)
while (@id <= @idmax)
begin
    select @amounttotal = sum(amount1 + amount2 + amount3) 
                          from amountinfo where id=@id
    -- do something with @amounttotal
    select @id=@id+1
end

Is there a way to factor out the while loop with some kind of complex select statement here? I am experienced with C/C++/C# programming but SQL is kinda new to me. Thanks!

EDIT: basically the "--do something" part involves inserting the individual @amounttotals into another table. The actual query I'm running is more complicated than that but I'm hoping to solve this simple problem first before posting a huge example of code.


try something like this:

INSERT INTO OtherTable
        (id, col1, col2, ...)
    SELECT 
        dt.id, t.col1, dt.TotalSum
        FROM (SELECT
                  id, SUM(t.amount1 + t.amount2 + t.amount3) AS TotalSum
                  FROM AMOUNTINFO
                  GROUP BY id
                  WHERE id>=@id AND id<=@idmax
             ) dt
            INNER JOIN  AMOUNTINFO t ON dt.id=t.id


You don't need the WHILE loop, use:

SELECT @amounttotal = SUM(t.amount1 + t.amount2 + t.amount3)
  FROM AMOUNTINFO t
 WHERE t.id BETWEEN @id AND @idmax

...but you need to describe what you're doing in the WHILE loop to the @amounttotal variable for us to help you further.

0

精彩评论

暂无评论...
验证码 换一张
取 消