Friday, December 31, 2010

Mimicing for loop in SQL

Many a times I've came across situations when I really hated SQL server for not providing "for loops". But once I thought did it stop me from implementing one? The answer that I got is stated below.
As we all know that if we want to loop through a result set we have to use Cursors, which many a times take the juice out of your Query performance.
Then how do we loop through the result set? For this we will make while loop to mimic like for loop.
For achieving this we will need three extra variables: 2 integer variables and one temporary table and follow the below steps
1. Store the result set into temporary variable in following manner
     Select Column1, Column2,
     Row_Number() over (order by Column1) as RowNo
     into #temp
     from table1
2. Declare a int variable and store the number of rows retrieved in this variable
     Declare @TotalRowCount  as int
     Set @TotalRowCount = @@RowNumber
3. Declare a int variable for counting number of rows looped.
     Declare @Counter as int
     Set @Counter = 1
4.  Use while loop to traverse through the temporary table we created above
      While @Counter <= @TotalRowCount
      Begin
           Select *
from #temp
where RowNo = @Counter
-- Perform the required operation
Set @Counter = @Counter + 1
      End
5. Complete the remaining operations.
6. Drop temporary table created for at end of your query
     Drop table #temp

Well, it worked for me hope works for others.

No comments:

Post a Comment