Login or Sign Up to become a member!
LessThanDot Sit Logo

LessThanDot

Data Management

Less Than Dot is a community of passionate IT professionals and enthusiasts dedicated to sharing technical knowledge, experience, and assistance. Inside you will find reference materials, interesting technical discussions, and expert tips and commentary. Once you register for an account you will have immediate access to the forums and all past articles and commentaries.

LTD Social Sitings

Lessthandot twitter Lessthandot Linkedin Lessthandot friendfeed Lessthandot facebook Lessthandot rss

Note: Watch for social icons on posts by your favorite authors to follow their postings on these and other social sites.

Your profile

    Search

    XML Feeds

    Google Ads

    « SQL Server DBA Tip 13 – SQL Server built in DR/HA SolutionsSQL Server DBA Tip 12 – SQL Server Tuning – Missing Index DMV »
    comments

    Please leave me a comment if you have written or have seen a trigger that is written in such a way that it will send an email when a value changes in a table.

    I am looking at the following question: Email trigger when data is changed

    1. ALTER TRIGGER [dbo].[RVABestellingenAantalWijzigenTrigger]
    2. ON [dbo].[RVA_Bestellingen]  
    3. AFTER UPDATE
    4. AS
    5. --Vars
    6. DECLARE @body varchar(500)
    7. DECLARE @BestellingID int
    8. DECLARE @CategorieID int
    9. DECLARE @SubCategorieID int
    10. DECLARE @AantalOrigineel int
    11. DECLARE @AantalNieuw int
    12. DECLARE @LocatieNaam varchar(255)
    13. DECLARE @ComponentNaam varchar(255)
    14. DECLARE @CategorieNaam varchar(255)
    15. DECLARE @SubCategorieNaam varchar(255)
    16. DECLARE @Datum datetime
    17.  
    18. if update(Aantal) /*and (SELECT Datum FROM inserted) = cast(floor(cast(dateadd(day,1,getdate()) as float)) as datetime)  */ and   (convert(varchar,getdate(),108)>'11:00')
    19. begin
    20.  
    21.     --Zetten aantallen
    22.     SET @AantalOrigineel            = (SELECT Aantal FROM deleted)
    23.     SET @AantalNieuw                = (SELECT Aantal FROM inserted)
    24.     SET @BestellingID               = (SELECT BestellingID FROM inserted)
    25.     SET @CategorieID                = (SELECT CategorieID FROM inserted)    
    26.     SET @SubCategorieID             = (SELECT SubCategorieID FROM inserted)
    27.  
    28.     --Zetten locatienaam en componentnaam
    29.     SELECT @LocatieNaam = ('RVA Aanpassingen Locatie: '+LocatieNaam), @ComponentNaam=OfficieleNaam, @Datum=Datum
    30.     FROM RVA_Bestellingen r
    31.     LEFT OUTER JOIN Locaties l on l.LocatieID = r.LocatieID
    32.     LEFT OUTER JOIN Componenten c on c.ComponentID = r.ComponentID
    33.     WHERE r.BestellingID = @BestellingID    
    34.  
    35.  
    36.     SELECT @CategorieNaam = Categorie
    37.     FROM RVA_HoofdCategorie
    38.     WHERE HoofdCategorieID = @CategorieID  
    39.  
    40.     SELECT @SubCategorieNaam = Categorie
    41.     FROM dbo.RVA_SubCategorie
    42.     WHERE SubCategorieID = @SubCategorieID      
    43.  
    44.     --Zet boyd
    45.     SET @body = (
    46.                     SELECT
    47.                         'HoofdCategorie: ' + @CategorieNaam+ char(10)+char(13)
    48.                         +'SubCategorie: ' + @SubCategorieNaam+ char(10)+char(13)
    49.                         + 'Componentnaam: '
    50.                         + @ComponentNaam + char(10)+char(13)
    51.                         + 'Origineel aantal: '
    52.                         + CAST(@AantalOrigineel as varchar(50) ) + char(10)+char(13)
    53.                         + 'Nieuw aantal: '
    54.                         + CAST(@AantalNieuw as varchar(50) ) + char(10)+char(13)
    55.                         + 'Leverdatum: ' +
    56.                         + convert(varchar(50),@Datum,105)                      
    57.                 )
    58.  
    59.     --Mailen naar Adeline
    60.      EXEC master..xp_sendmail
    61.             @recipients = 'fake@fake.fake',
    62.             @message    = @body,
    63.             @subject    = @LocatieNaam
    64. end

    And I am just shaking my head, for one it doesn't take into account muliple rows being updated, see Best Practice: Coding SQL Server triggers for multi-row operations for more on that topic

    The second bad thing is of course that you want your trigger to complete as fast as possible, you don't want it to email a bunch of people. What if the email blows up?
    Ideally you would write a query inside the trigger that dumps the desired results into another table, then you would have a job that checks that table every minute or so and does the emailing.

    Now I admit, I have written a trigger in the past that emailed when something got inserted, this was a table that would interact with Great Pains Plains. Once we decided to insert nine thousand rows as a stress test from a batch, and yes we brought down the whole exchange server, the email went out to I believe 20 people, this was the time of 3 MB inboxes :-)

    Lastly this person is on SQL Server 2008 and is still using xp_sendmail and not sp_send_dbmail

    Enough ranting, leave me a comment if you do send emails from withing triggers. If you do so, did you ever have any problems with it?

    *** If you have a SQL related question try our Microsoft SQL Server Programming forum or our Microsoft SQL Server Admin forum

    About the Author

    User bio imageDenis has been working with SQL Server since version 6.5. Although he worked as an ASP/JSP/ColdFusion developer before the dot com bust, he has been working exclusively as a database developer/architect since 2002. In addition to English, Denis is also fluent in Croatian and Dutch, but he can curse in many other languages and dialects (just ask the SQL optimizer) He lives in Princeton, NJ with his wife and three kids.
    Social SitingsTwitterFacebookLinkedInHomePageFlickrLTD RSS Feed
    1598 views
    Instapaper

    9 comments

    Comment from: Brent Ozar [Visitor] · http://www.brentozar.com
    Brent Ozar HAHAHA, wow, that is indeed awesome. It's like Reporting Services, but without the scalability.
    05/11/11 @ 07:46
    Comment from: SQLDenis [Member] Email
    SQLDenis Would be a nice piece of code for an interview/exam.....how many problems do you see in this code?
    05/11/11 @ 08:19
    Comment from: Ted Krueger (onpnt) [Member]
    Ted Krueger (onpnt) Almost makes you hope someone causes an update every second for a week. In fact, Brent has a good idea for the OP. Tell them to start up a SSRS subscription with sp_start_job in the trigger, generate the report to pdf, read the report in the trigger with MORE xp_ junk and then email that! Wow, I'm surprised I could even make that up

    Can we please get out of the xp_ 80 comp usage already?
    05/11/11 @ 08:21
    Comment from: riverguy [Member] Email
    riverguy I don't recall seeing it in person, but questions on how to do this come up from time to time in forums. Sometimes the OP will be convinced it's a bad idea, sometimes not.
    05/11/11 @ 08:24
    Comment from: Chris [Visitor]
    Chris If you absolutely needed an email, it would be better to have the trigger code create a log entry on another table, and then have a job that runs every so often which checks for new records, sends a single email notifying of all changes since the last email, and then flags those log records as emailed. This way the data update operation could work instantly, you'd still get your emails and best of all, you have a complete log of all changes that isn't stored in your inbox. =)
    05/11/11 @ 08:59
    Comment from: SQLDenis [Member] Email
    SQLDenis Chris, yes that would be my approach as well
    05/11/11 @ 09:32
    Comment from: niikola [Member] Email
    niikola And you know what was the answer I've got after I dare to propose using log table and job approach?

    "You do not know our business needs. Every delay in sending mails could cost us a lot of money, appart from going through log table to send thousands of e-mails will take unacceptable long time."
    :-o
    05/12/11 @ 02:05
    Comment from: SQLDenis [Member] Email
    SQLDenis niikola,

    That is pretty funny (or sad, depending how you look at it)
    05/12/11 @ 04:41
    Comment from: Paul Kuriakose [Visitor]
    Paul Kuriakose Yes this is the work of the devil.

    Patient: "Doctor, it hurts when I do this."

    Doctor: "Don't do that."
    05/12/11 @ 13:01

    This post has 1 feedback awaiting moderation...

    Leave a comment


    Your email address will not be revealed on this site.

    Your URL will be displayed.
    (Line breaks become <br />)
    (Name, email & website)
    (Allow users to contact you through a message form (your email will not be revealed.)