while循环中的表变量并非每次都初始化:SQL Server [英] Table variables inside while loop not initializing everytime : SQL Server

查看:195
本文介绍了while循环中的表变量并非每次都初始化:SQL Server的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am wondering why the table variables inside while loop does not behave like other variables. Table variables created only once and will be used across through out whole looping. but other variables getting initialized every time when loop increases.

查看下面的代码以获取更多信息

Check out the below code for more info

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

这是一个错误吗?

推荐答案

您的前提是错误的.每次遇到声明语句时,其他变量也不会重新初始化.

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

打印

1
2
...
9
10

这篇关于while循环中的表变量并非每次都初始化:SQL Server的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆