Unlimited Web Space

Enjoy Unlimited web hosting

Nov 7, 2011

How to use a 'while' loop in sql server.

In sql server, 'while' loop is the most used loop and the most popular loop. Most programers also use it in stead of a 'for' loop. Suppose, you need to do a task for n number of times like, 'while' loop is successfully used:

The 'while' loop syntax in sql is:



while (boolean expression)
begin
do this; /*update/insert/delete/etc*/
increment/decrement
end

Eg.

declare @table as table(ID int identity(1,1),Name varchar(20))
declare @Cnt int set @Cnt=1
while (@Cnt < 10)
insert into @table
select Name from SomeTable where SomeTable_ID = @Cnt
set @Cnt = @Cnt + 1
end

NB: SomeTable is the table from where we are getting the name and SomeTable_ID is the ID. This query works in SQL Server.

No comments:

Post a Comment