To back up a bit, personally I'd not use the sql server mail and just hook directly to your MTA for a number of reasons.Having said that and having a glut of time, let's start simple.CREATE TABLE dbo.FOO(Accountid int, customer_name varchar(50), [order] varchar(50), quantity int, email varchar(50))GOCREATE TRIGGER dbo.FOO_update ON dbo.FOO AFTER UPDATEAS BEGIN SET NOCOUNT ON; -- Insert statements for trigger here SELECT I.orders, D.orders, I.email FROM INSERTED I INNER JOIN DELETED D ON D.accountid = I.accountidENDGOINSERT INTO fooSELECT 1 as accountID, 'bob' AS customer, 'start' AS orders, 50 AS qty, 'bob@your.uncle'
At this point, we have one entry in our table and a trigger that will print the old and new state, assuming [order] is the thing that will change. Executing the following statement will result in orders orders emailstep2 start bob@your.uncle
Make the trigger fireUPDATE FOOSET orders = 'step2'WHERE accountID = 1
At this point, you'd expect to send an email to the value in email with an indication that their transaction is now in step2? If so, then you'll just do some TSQL string work in the trigger to make it look likeDECLARE @body varchar(255), @recipients varchar(50)SELECT @recipients = I.email, @body = 'Your order is now in a status of ' + I.[order]FROM INSERTED I
That's all well and good, but what about this scenario?-- create 2 new entitiesINSERT INTO fooSELECT 2 as accountID, 'robert' AS customer, 'start' AS orders, 50 AS qty, 'robert@your.uncle'UNION ALLSELECT 3 as accountID, 'alice' AS customer, 'start' AS orders, 50 AS qty, 'alice@your.aunt'-- Perform a mass updateUPDATE fooSET orders = 'step 3'
That will result in orders orders emailstep 3 start alice@your.auntstep 3 start robert@your.unclestep 3 step2 bob@your.uncle
Oh crap, you just sent one email instead of 3 and didn't even know you missed the other two. So in the case of mass updates, you'll need to do cursor logic in the trigger (unless someone has an alternative) to send an email for each item. The cursor in a trigger to send email on update is just begging to degrade your system performance.That help you see how to make it work with your data and hopefully provide a word of caution about the road you're going down?