Solved

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

Posted on 2014-03-27
6
8,404 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
6 Comments
 
LVL 21

Accepted Solution

by:
Dale Burrell earned 500 total points
ID: 39960638
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
ID: 39960753
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
ID: 39961337
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
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
LVL 21

Expert Comment

by:Dale Burrell
ID: 39961352
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
ID: 39961354
Yeah I noticed that.  Thanks.
0
 

Author Closing Comment

by:sxxgupta
ID: 39961356
Thank you very much
0

Featured Post

Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Load balancing is the method of dividing the total amount of work performed by one computer between two or more computers. Its aim is to get more work done in the same amount of time, ensuring that all the users get served faster.
In this article we will learn how to fix  “Cannot install SQL Server 2014 Service Pack 2: Unable to install windows installer msi file” error ?
Familiarize people with the process of retrieving data from SQL Server using an Access pass-thru query. Microsoft Access is a very powerful client/server development tool. One of the ways that you can retrieve data from a SQL Server is by using a pa…
Using examples as well as descriptions, and references to Books Online, show the documentation available for datatypes, explain the available data types and show how data can be passed into and out of variables.

724 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