Table variables inside while loop not initializing everytime : SQL Server

空扰寡人 提交于 2019-12-05 10:15:48

Your premise is wrong. Other variables don't get reinitialised every time the declare statement is encountered either.

set nocount on

declare @tt int
set @tt =10
while @tt>0
begin

        declare @i int

        set @i = isnull(@i,0) + 1
        print @i
        set @tt=@tt-1

end

Prints

1
2
...
9
10

As expected

SQL Server variable scope is per batch or the entire function/procedure/trigger, not per black/nested construct

http://msdn.microsoft.com/en-us/library/ms187953.aspx:

The scope of a variable is the range of Transact-SQL statements that can reference the variable. The scope of a variable lasts from the point it is declared until the end of the batch or stored procedure in which it is declared.

Though it is old post just wann add my comments

set nocount on
declare @tt int
set @tt =10
while @tt>0
begin
        declare @i int=0
        set @i = @i + 1
        print @i
        set @tt=@tt-1
end

Results:
1
1
1
1
1
1
1
1
1
1

If you want to load the table variable each time the loop executes. DROP FROM @Tablevariable once work done within the loop.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!