I’m not sure when it is appropriate to use a cursor.
I need to send out emails after a certain stored procedure is ran that updates some tables. So if
table1.field1 = "value" and
(select count(*)
from table1 join table2
on table2.table1_id = table1.id) > 20
then an email needs to be sent out for everything in table1 that meets those conditions. And in the email I need to include table1.field2 and table2.field3 and so on…
The only way I can think to do this is get my dataset of rows in table1 that meet these conditions and then use a cursor to go through it. I’ve never worked with sending emails from SQL Server before and I don’t know my options… I have never used a cursor before (although I do understand how) because I learned to shy away from them.
Thanks.
Edit:
With the while loop: So… I probably want to shove all the info i need into a temp table (select * from table1 where (conditions)) and then start a while loop that goes through each row of the resulting data set in my temp table. (WHILE i = 1 to (select count(*) from #temp) / assemble e-mail send e-mail / next)… then what is the best way to reference/point to which row of #temp I should be using for each loop iteration? I could just give #temp an identity(1,1) or use row_number()… right? I guess? It seems like I’m just trying to program my own cursor by doing this, though? And let’s say we set @subject = (select ‘Site ‘ & field2 & ‘ has a value of ‘ & field1 from #temp where temp_id_or_row_number = @i) and then increment @i for each loop…?
I have used something similar to this article
I used to build up straight html and then use that in an html formatted mail using
sp_send_dbmail.These stored procedures can get messy
I never used cursors – had several stored procs which had WHILE loops sending out multiple emails
Here’s a full example; hope it helps: