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??
Though it is old post just wann add my comments
Your premise is wrong. Other variables don't get reinitialised every time the declare statement is encountered either.
Prints
If you want to load the table variable each time the loop executes. DROP FROM @Tablevariable once work done within the loop.
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: