Tuesday, April 1, 2014

Loop in T-sql using Temporary Table and while loop equivalent to Foreach loop.

This post will explain you the process of performing Foreach equivalent loop using Temporary Table and while loop iteration through the temporary table.
Usage:
1. To achieve loop without use of cursor.
2. To achieve Foreach like functionality i.e. can get current row in the loop.
3. Insert data in some table in bulk for no of fixed range like in case of fixed customer billing, Student bill assign.
First You need to create a temporary table with auto increment integer as primary key and second column for the data you are going to check loop on.
 ex.

CREATE TABLE #temp(
uniqueid smallint Primary Key IDENTITY(1,1)
 ,col1       INT
);


Now we can insert data in the temporary table trough which we are going to traverse.

insert into #temp (col1  )
select customerid from skhpcustomer;


After having data in temporary table now we are all set to go for a loop for which we can set an integer flag to get current row.

declare @i int=1;
while(@i<=(select max(uniqueid) from #temp))
begin

--Here Other task on data can be performed by getting col1 for uniqueid in #temp
print @i;

set @i=@i+1;
end

Drop table #temp
-- Donot forget to clear un wanted temp data.

This completes the loop which is equivalent to foreach loop required for different condition in SQL Development.