Friday, March 23, 2012

Loop within a stored procedure

Hi,

Can I have a FOR loop within a stored procedure. Basically I want 2 loop through each user and send them an automatic email using Server Agent.

thanksThere's no FOR loop, but there is a WHILE loop. Look in BOL for full documentation on its use (I don't think I've ever actually used it, except in one or two rare cases where I broke down and used a cursor. Ah, foolish youth!)|||If you want to loop though a dataset, use a cursor:

declare NextRow cursor local for
select EmailAddress
from Table
where ...

open NextRow

and then you can get the rows one by one using fetch:

fetch next from NextRow into @.EmailAddress

Remember to check @.@.fetch_status to see if you're done.

if @.@.fetch_status = -1 -- you're done!
if @.@.fetch_status = -2 -- This row has been deleted.

Does this help?

No comments:

Post a Comment