Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Table variables inside while loop not initializing everytime : SQL Server

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

is this a bug??

like image 378
RameshVel Avatar asked Sep 20 '10 11:09

RameshVel


People also ask

What is the alternative for while loop in SQL Server?

As you can see, CTEs is an alternative in many situations to replace the WHILE loop. We could also use Sequences, but CTE covers and substitutes the while in more situations than the sequences.

Are SQL variables scoped?

Variables have local scope and are only visible within the batch or procedure where they are defined.


2 Answers

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
like image 72
Martin Smith Avatar answered Oct 02 '22 07:10

Martin Smith


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.

like image 21
gbn Avatar answered Oct 02 '22 07:10

gbn