Sunday, April 28, 2013

SQL SERVER WHILE LOOP

While loops in SQL SERVER T-SQL

            while loops are mainly used for executing block of sql statements for specified number of times.

SYNTAX:
  while condition
   begin
            block of  sql statements
   end;


For ex: Print Even numbers from 1 to 20 using while loop.


declare @counter int=1;

while @counter <=20
begin

if (@counter % 2 = 0)
print 'even number'+cast(@counter as varchar(2));


set @counter=@counter+1;
end

OUTPUT
even number2
even number4
even number6
even number8
even number10
even number12
even number14
even number16
even number18
even number20

For ex: Print ODD numbers from 1 to 20 using while loop.

 declare @counter int=1;

while @counter <=20
begin

if (@counter % 2 <> 0)
print 'odd number'+cast(@counter as varchar(2));

set @counter=@counter+1;
end


OUTPUT
odd number1
odd number3
odd number5
odd number7
odd number9
odd number11
odd number13
odd number15
odd number17
odd number19



3 comments: