Tuesday 13 October 2015

Best examples of loop in Sql Server with syntax

For those who doesn't want to implement cursor in Sql server can use simple traditional loop and condition statement in sql server to achieve his task.

If condition in Sql server with goto statement to print one to ten

       
begin
declare @counter int = 0;
repeat:
if @counter < 10
begin
 print @counter
 set @counter = @counter + 1;
 goto repeat
end
end
  
 


While loop in sql server to print 1 to 10

       
begin
declare @counter int = 0;
while @counter < 10
begin
 print @counter
 set @counter = @counter + 1;
end
end
  
 

Print all tables one by one using while loop and set NOCOUNT on

       
begin
 SET NOCOUNT ON;
 select name into #temptable from sys.tables
 declare @TableID int

while exists (select * from #temptable)
begin
 declare @name varchar(100) = '';
    select top 1 @name = name  from #temptable;
 print @name;
 delete #temptable where name=@name;
end
drop table #temptable
end
  
 

Example Query with and without NOCOUNT