Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Cursor in sp_send_dbmail

Author  Topic 

mulletron
Starting Member

3 Posts

Posted - 2013-08-07 : 15:04:00
Hi all,

I have been looking through other posts to try to piece together a solution but have not had the luck I hoped. Wondering if someone can review my code here and let me know where I am going wrong.

I basically have a table with 4 fields:
PO Number, Shipment Number, Tracking Number, Email

I am hoping to cycle through each row of this table and send an email to the address in the 4th field with the information in the first 3. Even if 2 rows have the same email address, I would want 2 separate emails. Doesn't seem to hard, but still struggling. Right now, it is sending one email to the first address with all the records in the table in the email. Below is my current code


DECLARE @xml NVARCHAR(MAX)
DECLARE @body NVARCHAR(MAX)
DECLARE @Shipment NVARCHAR(MAX)
DECLARE @TrackingNo NVARCHAR(MAX)
DECLARE @Email NVARCHAR(MAX)

DECLARE EmailCursor Cursor for
(select [SHIPMENT], [TRACKING_NO], [E-Mail]
FROM AME_TRACKING_EMAIL)

open EmailCursor
Fetch next from EmailCursor
INTO @Shipment, @TrackingNo, @Email
While (@@FETCH_STATUS = 0)
Begin

SET @xml = CAST((select [External Document No_] as 'td','', [SHIPMENT] as 'td', '', [TRACKING_NO] as 'td'
FROM AME_TRACKING_EMAIL
FOR XML PATH('tr'), ELEMENTS ) AS NVARCHAR(MAX))


SET @body ='<html><body>Blah blah blah'

SET @body = @body + @xml + '<br> More blah blah blah </body></html>'

USE msdb
EXEC sp_send_dbmail
@profile_name='Profile',
@recipients = @Email,
@subject = 'Your Order Had Shipped!',
@body = @body,
@body_format='HTML',
@execute_query_database = 'SQL-TEST'

FETCH NEXT FROM EmailCursor INTO @Shipment, @TrackingNo, @Email
END
Close EmailCursor
Deallocate EmailCursor

mandm
Posting Yak Master

120 Posts

Posted - 2013-08-07 : 15:44:10
Not sure on this but try moving your END statement above the FETCH NEXT.
Go to Top of Page

mulletron
Starting Member

3 Posts

Posted - 2013-08-07 : 15:57:30
I appreciate the response...but this ran for about 15 sec before I killed it - and it sent me over 10K emails. I think there may be another issue with the code :)
Go to Top of Page

mandm
Posting Yak Master

120 Posts

Posted - 2013-08-07 : 16:06:26
How many rows are there in your AME_TRACKING_EMAIL table?

Go to Top of Page

mulletron
Starting Member

3 Posts

Posted - 2013-08-07 : 16:15:50
Just 2 with different shipments, tracking no, and emails for each row.
Go to Top of Page

mandm
Posting Yak Master

120 Posts

Posted - 2013-08-07 : 18:01:52
See Sunita Beck's resonse in this link.

http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=158847
Go to Top of Page
   

- Advertisement -