Link to home
Start Free TrialLog in
Avatar of hessfirm01
hessfirm01

asked on

SQL Cursor and sp_send_dbmail

I'm have been able to send a View that display's multiple records in a nice table based on certain criteria. I use sp_send_dbmail and MSSQL 05

What I can't figure out, is how to send to the email address associated with those records, not a static one, then loop through and send the next result set to the next recipient.

In the code below, i've declared a static @recipients...but i want it to be pulled from the joined table, and i want it to loop to the next record set. So in the joined tables, 1 email will be associated with, let's say, 10 records...etc.

I think this is a cursor thing...not sure. Any ideas?
DECLARE @tableHTML  NVARCHAR(MAX) ;
 
SET @tableHTML =
    N'<H1>Work Order Report</H1>' +
    N'<table border="1">' +
    N'<tr><th>Work Order ID</th><th>Product ID</th>' +
    N'<th>Name</th><th>Order Qty</th><th>Due Date</th>' +
    N'</tr>' +
    CAST ( ( SELECT td = m.ln,       '',
                    td = m.Lot, '',
                    td = m.Br, '',
                    td = m.Baf, '',
                    td = m.Lp, ''
              FROM mydb.dbo.table as m
              WHERE subd = 'village grove'
              ORDER BY lp ASC
              FOR XML PATH('tr'), TYPE 
    ) AS NVARCHAR(MAX) ) +
    N'</table>' ;
 
 
EXEC msdb.dbo.sp_send_dbmail
	@profile_name = 'local',
	@recipients='myemail@gmail.com',
    @subject = 'Current Homesites',
    @body = @tableHTML,
    @body_format = 'HTML' ;

Open in new window

Avatar of hessfirm01
hessfirm01

ASKER

I probably would need to group this as well...so when the view displays the same email address for a group of houses for sale in the same community, that one email address gets one email of the list of houses.
ASKER CERTIFIED SOLUTION
Avatar of BrandonGalderisi
BrandonGalderisi
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Brilliant!!!!!!!!

Question on the above code...the field on line 29 is a money field...i'm try to cast/convert it...because i don't want it to show 4 decimal places...but T-SQL doesn't like this...so on line 29, i'm trying something like this:
                    td = m.cast(urMoneyColumn as numeric(12,2)), ''

doesn't work though. any thoughts?
Avatar of Chris Luttrell
the "m." is misplaced.  either leave it off or it should be on the column name inside
                    td = cast(m.urMoneyColumn as numeric(12,2)),