Solved

SQL trigger code to send an email to a recipient

Posted on 2014-03-26
11
950 Views
Last Modified: 2014-03-26
Need help to create a sql trigger code to send an email to    test@gmail.com     with subject heading "New SCAR <number> (whatever this new number is after insert) generated"    and message of the body is        "The SCAR is for <AreaRequiringCA>

<number> is the SCAR_No field value for a new insert and <AreaRequringCA> is a ntext in design.

So I would like the message to go only after an insert of a new SCAR_No has been created and the <AreaRequirintgCA> goes from null to some ntext value.  The table is called "SCARLogCopy"

No idea how to do this.  This email will occur like once in two weeks at most.
1.gif
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
  • 6
  • 4
11 Comments
 
LVL 34

Expert Comment

by:ste5an
ID: 39957019
You should not do that. While you can use database mail in a trigger, you need to consider three things:

1. E-mail is unreliable and asynchronous. So sending it in a trigger makes no sense.
2. The trigger may lock due to longer execution time.
3. The trigger may rollback due to errors in the sending process.

Use a separate process instead. E.g. SQL Server Agent or a scheduled task or your own Windows Service.
0
 
LVL 40

Expert Comment

by:lcohan
ID: 39957040
It would be something like:

CREATE TRIGGER [TI_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 AreaRequringCA FROM inserted);
DECLARE @s_sub nvarchar(1000)
set @s_sub = 'New SCAR ' + @number+ ' was generated';
EXEC msdb.dbo.sp_send_dbmail
      @profile_name = 'yourmailprofile',
      @recipients = 'you@email.com',
      @subject = @s_sub,
      @body =  @sqlstr
END
GO

Sorry - that was for update. Use this one instead for your specific request
0
 

Author Comment

by:sxxgupta
ID: 39957205
Almost there:

What is @profile_name or where do I get that from
0
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

 
LVL 40

Expert Comment

by:lcohan
ID: 39957225
You need to configure database mail on that server and you can do that via SSMS.
If it's already configured you should be able to see that in the same wizard or just run query below to list profiles on that SQL Server.

exec msdb.dbo.sysmail_help_profile_sp;


After you get the profile name you want to use just replace that string with your profile name and the actual email addresses separated by ; in that @recipients  string.
0
 

Author Comment

by:sxxgupta
ID: 39957251
ok did that

now when I run the trigger I get:

Msg 208, Level 16, State 6, Procedure TI_SCARLogCopy, Line 14
Invalid object name 'dbo.TI_SCARLogCopy'.

and faulting at the line

EXEC msdb.dbo.sp_send_dbmail
0
 
LVL 40

Expert Comment

by:lcohan
ID: 39957277
<<
now when I run the trigger I get:

Msg 208, Level 16, State 6, Procedure TI_SCARLogCopy, Line 14
Invalid object name 'dbo.TI_SCARLogCopy'.
>>


Did you selected the appropriate database ?

Did you executed the CREATE TRIGGER or ALTER TRIGGER? From what I see I believe you RAN either an ALTER and trigger is not there or ALTER in a different database.

OR...check is the name of the trigger was not between square brackets because then its name would be [dbo.TI_SCARLogCopy] instead of dbo.[TI_SCARLogCopy]
0
 

Author Comment

by:sxxgupta
ID: 39957302
I executed this:

USE [QA]
GO
/****** Object:  Trigger [dbo].[TI_SCARLogCopy]    Script Date: 03/26/2014 16:04:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER TRIGGER [dbo].[TI_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 = 'SanjayGupta',
      @recipients = 'sgupta@zoll.com',
      @subject = @s_sub,
      @body =  @sqlstr
END


and got the same error......sorry I am new to this.  Do I need to first create the trigger then alter it.......
0
 

Author Comment

by:sxxgupta
ID: 39957344
ok, running the trigger did not give errors.   I ran your original code posting.  Waiting for the email now................
0
 
LVL 40

Accepted Solution

by:
lcohan earned 500 total points
ID: 39957408
You can check SQL mail sent items by:

select * from msdb..sysmail_sentitems;

and unsent mail by:

select * from msdb..sysmail_unsentitems


If the mail was SENT by SQL and you do not get it then you need to check with someone that is taking care of the SMPT server.
0
 

Author Comment

by:sxxgupta
ID: 39957559
select * from msdb.dbo.sysmail_sentitems;


ran this with no records returned......so no mail was sent, correct?

thx.

Sanj
0
 

Author Comment

by:sxxgupta
ID: 39957574
hahahaha

SMTP server address was wrong.  Corrected and email came thru.

Thanks very much!!!!!

Sanj
0

Featured Post

Visualize your virtual and backup environments

Create well-organized and polished visualizations of your virtual and backup environments when planning VMware vSphere, Microsoft Hyper-V or Veeam deployments. It helps you to gain better visibility and valuable business insights.

Question has a verified solution.

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

How to leverage one TLS certificate to encrypt Microsoft SQL traffic and Remote Desktop Services, versus creating multiple tickets for the same server.
Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.
Viewers will learn how to use the UPDATE and DELETE statements to change or remove existing data from their tables. Make a table: Update a specific column given a specific row using the UPDATE statement: Remove a set of values using the DELETE s…

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