Pages

Monday, March 11, 2013

SQL Loop through a table variable in SQL

Declare @Id int

While EXISTS(Select Count(*) From ATable Where Processed = 0)
Begin
    Select Top 1 @Id = Id From ATable Where Processed = 0

    --Do some processing here

    Update ATable Set Processed = 1 Where Id = @Id 

End
Another alternative is to use a temporary table:
Select *
Into   #Temp
From   ATable

Declare @Id int

While EXISTS(Select Count(*) From #Temp)
Begin

    Select Top 1 @Id = Id From #Temp

    --Do some processing here

    Delete #Temp Where Id = @Id

End
 
Continue Reading...   

No comments:

Post a Comment