简体   繁体   中英

How to create a trigger to send email when a new record is added in to the table

When I run an interface with name 'personimport' it will generate a new record in the table (run history).

There are 5 columns in the table:

interface-id, interface name, date, personid, error msg

Inserting "1, qwerty, 2019-09-11, a1" is successful, but inserting "2, person import, 2019-09-12, a2" throws an error .

Whenever a new record is added into this table with the name 'person import' I want to send an email to set of employees.

How to write a trigger for this in SQL Server?

You need to have database mail configured: https://docs.microsoft.com/en-us/sql/relational-databases/database-mail/configure-database-mail?view=sql-server-2017

You need to create a trigger:

  1. From SSMS goto the table and expand
  2. Right click triggers, and "New Trigger"
  3. Name your trigger, on table name, and after insert

     CREATE TRIGGER SendTheEmails ON runhistory AFTER insert AS BEGIN -- Insert statements for trigger here END GO 

    https://docs.microsoft.com/en-us/sql/t-sql/statements/create-trigger-transact-sql?view=sql-server-2017

    Then for the SQL to email:

     Declare @message varchar(max) Declare @subjectline varchar(60) set @subjectline = 'Your Subject' set @message = 'Your Message body' EXEC msdb.dbo.sp_send_dbmail @profile_name = 'dbmailProfileName' , @recipients = 'youremails@yourdomain' , @subject = @subjectline , @body_format = 'html' , @body = @message 

Obviously you can declare other variables, and use the insert table for further information.

Yeah, and as Fillburt said, this seems like a duplicate of Send e-mail from a trigger

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM