简体   繁体   中英

SQL Server: Sum up total value of local variable inside WHILE loop

May I know how to write a statement to sum up the total value from different n in a WHILE loop in SQL Server?

Following is my code:

Declare n int = 0
    WHILE (n<5)
        IF ( @fruit = 'Apple')
            SET @price = 2
        IF ( @fruit = 'Banana')
            SET @price = 3
    SET n = n+1
        END

How can I sum up all the price from n = 0 to n = 4?

What I tried:

Declare n int = 0
SET @price = 0
WHILE (n<5)
        IF ( @fruit = 'Apple')
            SET @price = @price + 2
        IF ( @fruit = 'Banana')
            SET @price = @price + 3
    SET n = n+1
        END

But it only returns the price at last iteration n=4

Seems your query is right and it yield the right result as you can validate in below fiddle.

DB FIDDLE

SET NOCOUNT ON
DECLARE @loop INT
DECLARE @price INT
SET @price = 0
SET @loop = 1

WHILE @loop <= 5
BEGIN
    IF (@fruit = 'Apple')
       SET @price = @price + 2
    IF (@fruit = 'Banana')
       SET @price = @price + 3
    SET @loop = @loop +1
END

Instead of loop, you can re write like below

SET NOCOUNT ON
DECLARE @Price INT = 0     
IF (@fruit = 'Apple')
BEGIN
     SET @price = 5 * 2
END
IF (@fruit = 'Banana')
BEGIN
     SET @price = 5 * 3
END

Try this:

Declare @n int = 0
Declare @fruit varchar(50)='apple'
declare @price int=0
   WHILE (@n<5)
   BEGIn
        IF ( @fruit = 'Apple')
            SET @price = @price + 2
        IF ( @fruit = 'Banana')
            SET @price = @price + 3
    SET @n = @n+1
    print @price
        END

Output:

2  
4  
6  
8  
10  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM