foreach loops in SQL

01 Jul 2011

Tutorial T-sql

If you don’t want to use a cursor, here is a strategy that should work…

use BeatTheBookie
 
--Build up the list to iterate over
set rowcount 0 
select distinct NULL mykey, Name into #foreachTeam from dbo.Team
 
--update the pointer for the first element in the list
set rowcount 1 
update #foreachTeam set mykey = 1
 
while @@rowcount > 0 
begin 
    set rowcount 0
 
    --Do what you need to here for each item in the list
 
    --pop the current item off the list
    delete from #foreachTeam where mykey = 1 
 
    --update the pointer to the next item in the list
    set rowcount 1 
    update #foreachTeam set mykey = 1 
 
end 
set rowcount 0

See here for more information: http://support.microsoft.com/kb/111401/en-gb