Solved

SQL trigger to send an email to a person after an update

Posted on 2014-03-27
6
6,944 Views
Last Modified: 2014-03-28
Need help to create a sql trigger code to send an email  with subject heading "Updated SCAR <number> (whatever this new number is after insert) generated"    and message of the body is        "The SCAR for <SCAR_No> for <AreaRequiringCA> has been changed from <AreaRequiringCA>.CurrentValue to <CarriageReturn> <CarriageReturn> to <AreaRequiringCA>.UpdatedValue.

SCAR_No field value (SCAR <number>) is an integer and a unique record identifier (primary key autonumber field) and <AreaRequiringCA> is a nvarchar(max) in design.

I have the code for the initial insert but do not know what to do with the  update for <AreaRequiringCA> field update.

No idea how to do this.  This email will occur like once in two weeks at most.


For a new record insert of a SCAR_No and emailing; here is the code that works fine.  Need one for the update event of the field <AreaRequiringCA> for a already existing SCAR_No.




use QA
go

CREATE TRIGGER [Email_SCARLogCopy] ON  [dbo].[SCARLogCopy]
   AFTER INSERT
AS
BEGIN

declare @number sysname;
set @number = (select SCAR_No from INSERTED);

DECLARE @sqlstr nvarchar(MAX)
SET @sqlstr = (SELECT AreaRequiringCA FROM inserted);
DECLARE @s_sub nvarchar(1000)
set @s_sub = 'New SCAR ' + @number+ ' was generated';
EXEC msdb.dbo.sp_send_dbmail
      @profile_name = 'SG',
      @recipients = 'sg@zl.com',
      @copy_recipients='sg@zl.com',
      @subject = @s_sub,
      @body =  @sqlstr
END
GO
0
Comment
Question by:sxxgupta
  • 3
  • 2
6 Comments
 
LVL 21

Accepted Solution

by:
Dale Burrell earned 500 total points
Comment Utility
Firstly your current trigger only works for single record updates - a common mistake when writing a trigger. The database itself handles multi-record inserts and updates and therefore any trigger you write should do also.

Secondly I'm confused about your SCAR_No - on one hand you say its the auto-generated ID for the record, on the other you say that its changed on update. Although you also say that the AreaRequiringCA is the field updated. So I have written the following assuming that the SCAR_No doesn't change. Regardless its unlikely to be perfect first off, but it hopefully gives you a starting point to build on.

CREATE TRIGGER [Email_SCARLogCopy] ON  [dbo].[SCARLogCopy]
   AFTER INSERT, UPDATE
AS 
BEGIN
  set nocount on

  declare @SCAR_No varchar(38), @s_sub nvarchar(1000), @sqlstr nvarchar(MAX)

  declare @updates table (SCAR_No varchar(38), AreaRequiringCA nvarchar(max), AreaRequiringCAOld nvarchar(max), IsInsert bit)

  insert into @Updates (SCAR_No, AreaRequiringCA, AreaRequiringCAOld, IsInsert)
    select I.SCAR_No, I.AreaRequiringCA, D.AreaRequiringCA, case when D.SCAR_No is null then 1 else 0 end
    from Inserted I
    left join Deleted D on D.SCAR_No = T.SCAR_No

  while exists (select 1 from @Updates) begin
    select top 1 @SCAR_No = SCAR_No
      , @sqlstr = case when IsInsert = 1 then AreaRequiringCA else 'The SCAR for ' + SCAR_No + ' for ' + AreaRequiringCA + ' has been changed from ' + AreaRequiringCAOld + ' to ' + char(13) + char(13) + ' to ' + AreaRequiringCA + '.' end
      , @s_sub = case when IsInsert = 1 then 'New SCAR ' + SCAR_No+ ' was generated' else 'Updated SCAR ' + SCAR_No + ' generated' end
    from @Updates
    exec msdb.dbo.sp_send_dbmail
      @profile_name = 'SG',
      @recipients = 'sg@zl.com',
      @copy_recipients='sg@zl.com',
      @subject = @s_sub,
      @body =  @sqlstr
    delete from @Updates where @SCAR_No = SCAR_No
  end
END
GO

Open in new window

0
 
LVL 35

Expert Comment

by:David Todd
Comment Utility
Hi,

Strongly suggest that you _not_ send the emails from a trigger.

Get the trigger to insert into a work table the relevant id's, and then get a SQL job to every minute or so scan the table for new ids, send the email, delete the id (or better, mark as sent)

If the trigger fires on a whole of table update, the waiting to send emails could be intolerable, and timeout, and the update/insert fail.

HTH
  David
0
 

Author Comment

by:sxxgupta
Comment Utility
I got this error:

Msg 4104, Level 16, State 1, Procedure Email_SCARLogCopy_Update, Line 12
The multi-part identifier "T.SCAR_No" could not be bound.

There is no T.SCAR_No
0
Backup Your Microsoft Windows Server®

Backup all your Microsoft Windows Server – on-premises, in remote locations, in private and hybrid clouds. Your entire Windows Server will be backed up in one easy step with patented, block-level disk imaging. We achieve RTOs (recovery time objectives) as low as 15 seconds.

 
LVL 21

Expert Comment

by:Dale Burrell
Comment Utility
Should be I.SCAR_No - I couldn't test it, so leaving it to you to debug... just giving you a starting point.
0
 

Author Comment

by:sxxgupta
Comment Utility
Yeah I noticed that.  Thanks.
0
 

Author Closing Comment

by:sxxgupta
Comment Utility
Thank you very much
0

Featured Post

Zoho SalesIQ

Hassle-free live chat software re-imagined for business growth. 2 users, always free.

Join & Write a Comment

JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
Slowly Changing Dimension Transformation component in data task flow is very useful for us to manage and control how data changes in SSIS.
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties
Using examples as well as descriptions, and references to Books Online, show the different Recovery Models available in SQL Server and explain, as well as show how full, differential and transaction log backups are performed

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now