Friday, March 7, 2008

Loop through SQL table

If you have a SQL result set that you would like to loop through, here is how you'd do it.


--Begin with defining the dataset you want to work with.
declare @res table (ID int, orderNum int)
insert into @res
select ID, orderNum
from A_Table a
inner join B_Table b on b.ID=a.ID
order by orderNum

declare @orderNum int

--Create the cursor that will cycle through the result set.
declare keys cursor for
select orderNum
from @res

open keys
fetch keys into @orderNum
while (@@fetch_status = 0)
begin
    exec orderDelete @orderNum
    fetch keys into @orderNum
end
close keys
deallocate keys

...And there you have it.

No comments: