每次循环时没有初始化的表变量:SQL Server

Ram*_*Vel 5 sql-server while-loop table-variable

我想知道为什么while循环中的表变量不像其他变量那样.表变量只创建一次,将在整个循环中使用.但是每当循环增加时,其他变量都会被初始化.

有关详细信息,请查看以下代码

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

        declare @temptable table(id int identity(1,1),sid bigint)
        insert into @temptable 
                select @tt union all
                select @tt + 1 

                select * from @temptable 
               --delete from @temptable
                set @tt=@tt-1
end
Run Code Online (Sandbox Code Playgroud)

这是一个错误?

Mar*_*ith 5

你的前提是错的.每次遇到declare语句时,其他变量都不会重新初始化.

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
Run Code Online (Sandbox Code Playgroud)

打印

1
2
...
9
10
Run Code Online (Sandbox Code Playgroud)