SQL Server Variable in SQL while loop doesn't increase

umuewwlo  于 2023-06-04  发布在  其他
关注(0)|答案(2)|浏览(155)

With code below, I'm only getting a 4 as result. If I change my set @ counter = 4 to set @counter=5 , I get only 5 in the end. I'm using SAP Business One query generator. How is this not working? If I put select @counter after END I actually get a 11 ... So the loop actually runs.

DECLARE @Counter int
SET @Counter = 4
WHILE @Counter <= 10
BEGIN
select @counter
SET @Counter = @counter + 1
END
lstz6jyr

lstz6jyr1#

Your code seems right to me... The problem might be in the manner you wrote the variable names. Try using same capitalization when its a single variable: @counter and @Counter.

Also try to use select instead of set. They do pretty much the same thing, but might work better in your case.

SELECT @Counter = @Counter + 1

Edit after reading comments: If your select outside the loop shows 11, try to print inside the loop instead of selecting just to check if it shows 4 too.

DECLARE @counter int
SET @counter = 4
WHILE @counter<= 10
BEGIN
    PRINT @counter
    SELECT @counter = @counter + 1
END
8zzbczxx

8zzbczxx2#

SAP Business One query manager just shows the result of the first select statement. In your case, you could store all the data in a temp table and select that table when you get out of the loop.

declare @temp table (mynum int)
DECLARE @Counter int
SET @Counter = 4
WHILE @Counter <= 10
BEGIN
   insert into @temp select @counter
   SET @Counter = @counter + 1
END

select * from @temp

相关问题