SQL Server 2014 INSERT trigger not firing (not sending mail) - sql-server

The trigger I am using is not firing, any ideas/help is appreciated. I checked the sysmail_allitems and its empty. To give some more explanation, I have a program where we submit travel requests through a form, when you submit a form a new row is created in TS_CUSTOM_TRVLBCK, everytime this happens I want an email to be sent with the conditions below. I have submitted a new form form (added image), the row is there but the trigger didnt fire.
My goal is to receive an email when one of the users in the where statement submits a request (a new row is created)
CREATE TRIGGER [dbo].[TS_TRAVEL_NEW_IIS]
ON [dbo].[TS_CUSTOM_TRVLBCK]
FOR INSERT
AS
BEGIN
SET NOCOUNT ON;
DECLARE #user Varchar(100)
DECLARE #subject Varchar(100)
DECLARE #body Varchar (200)
SELECT #user + RTRIM(TRVL_INITIATOR) FROM inserted;
SET #subject = 'New Travel Request - ' + #user
SET #body = 'Kindky note that user ' + #user + ' has submitted a new travel request.'
IF EXISTS (SELECT 1 FROM inserted WHERE [TRVL_INITIATOR] IN ('Luke Gatt','Marcelle Attard','Matthew Borg Dingli','Mark Schembri','Fiona Tesi','Charmaine Buttigieg','Stephen Mifsud','Tessabelle Cammilleri'))
BEGIN
EXEC msdb.dbo.sp_send_dbmail
#recipients = 'luke.gatt#mca.org.mt',
#profile_name = 'AbsenceMailer',
#subject = #subject,
#body = #body;
END
END
GO

Related

INSERT Trigger in SQL Server with condition [duplicate]

This question already has an answer here:
Send e-mail from a trigger
(1 answer)
Closed 1 year ago.
I'm trying to use an INSERT TRIGGER in an SQL Server db. It's my first trigger an I want to use it to send an email if certain value has been met in that inserted row:
CREATE TRIGGER dbo.SEND_MAIL
ON dbo.table
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON
IF (SELECT field1 FROM INSERTED) = '1'
BEGIN
EXEC msdb.dbo.sp_send_dbmail
#recipients = 'mail address',
#profile_name = 'profile1',
#subject = 'subject',
#body = 'body text';
END
END
If I try to execute the send_dbmail stored procedure with those email parameters, the email is sent perfectly. But not in the trigger.
I see that values that comply the condition in the IF statement (field1 = '1') are being inserted in the table. But can't figure out why is not working in the trigger.
I tried to use 'LIKE '1'' instead of equal in the IF but no luck.
Any hint to make it work?
Thank you so much in advance,
You can have many records in the inserted-table, so I would suggest you to write it like:
IF exists (SELECT field1 FROM INSERTED where field1='1')
BEGIN
EXEC msdb.dbo.sp_send_dbmail
#recipients = 'mail address',
#profile_name = 'profile1',
#subject = 'subject',
#body = 'body text';
END

is there a way i can get an alert whenever a table gets records in sql server

i have a table in SQl server which occasionally gets data from a linked server, and than i have to do activities on it .
but the problem is there is no way to check if the data is inserted in table (table is always truncated after performing the activity so next time when data is pushed table is already empty) i manually check daily for data if it is inserted or not .
what i want is to get auto alert on my email (i already have db_mail configured and working) whenever the data is pushed in a table .
i have sa admin and complete privileges on Database and also on Windows server 2012 R2
You can do this with a trigger but you will have to do some preparations with privileges so the executor (the login that's inserting the records on your tracking table) can send email correctly:
CREATE TRIGGER dbo.TrackingTableNameAfterInsert ON TrackingTable
AFTER INSERT
AS
BEGIN
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'YourConfiguredProfile',
#recipients = 'youremail#mail.com',
#subject = 'Records were inserted on TrackingTable',
#body = ''
END
You might want to encapsulate the email sending on an SP and configure it's permissions there.
In regards to the following:
...table is always truncated after performing the activity so next time
when data is pushed table is already empty...
You can create a historical table and use a trigger to also insert inserted records on this table, so the TRUNCATE or DROP of the original one won't affect the copied records.
CREATE TABLE TrackingTableMirror (
/*Same columns and types*/
InsertedDate DATETIME DEFAULT GETDATE())
GO
CREATE TRIGGER dbo.TrackingTableInsertMirror ON TrackingTable
AFTER INSERT
AS
BEGIN
INSERT INTO TrackingTableMirror (
/*Column list*/)
SELECT
/*Column list*/
FROM
inserted AS I
END
This way you can check all records on this mirrored table and not the volatile one (and avoid all the email sending).
1) Create Profile and Account
You need to create a profile and account using the Configure Database Mail Wizard which can be accessed from the Configure Database Mail context menu of the Database Mail node in Management Node. This wizard is used to manage accounts, profiles, and Database Mail global settings.
2) Run Query
sp_CONFIGURE 'show advanced', 1
GO
RECONFIGURE
GO
sp_CONFIGURE 'Database Mail XPs', 1
GO
RECONFIGURE
GO
3)
USE msdb
GO
EXEC sp_send_dbmail #profile_name='yourprofilename',
#recipients='test#Example.com',
#subject='Test message',
#body='This is the body of the test message.
Congrates Database Mail Received By you Successfully.'
through the table
DECLARE #email_id NVARCHAR(450), #id BIGINT, #max_id BIGINT, #query NVARCHAR(1000)
SELECT #id=MIN(id), #max_id=MAX(id) FROM [email_adresses]
WHILE #id<=#max_id
BEGIN
SELECT #email_id=email_id
FROM [email_adresses]
set #query='sp_send_dbmail #profile_name=''yourprofilename'',
#recipients='''+#email_id+''',
#subject=''Test message'',
#body=''This is the body of the test message.
Congrates Database Mail Received By you Successfully.'''
EXEC #query
SELECT #id=MIN(id) FROM [email_adresses] where id>#id
END
4) Trigger Code
CREATE TRIGGER [dbo].[Customer_INSERT_Notification]
ON [dbo].[Customers]
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON;
DECLARE #CustomerId INT
SELECT #CustomerId = INSERTED.CustomerId
FROM INSERTED
declare #body varchar(500) = 'Customer with ID: ' + CAST(#CustomerId AS VARCHAR(5)) + ' inserted.'
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'Email_Profile'
,#recipients = 'recipient#gmail.com'
,#subject = 'New Customer Record'
,#body = #body
,#importance ='HIGH'
END
I refer this link.

SQL email trigger sending query as text as opposed to the actual result

I've created a trigger on a table that send an email, however it sends the query as text as opposed to the actual results of the query.
Hopefully someone can tell me where I'm going wrong. Trigger is:
[dbo].[EventMail] ON [dbo].[Table1] AFTER INSERT AS
BEGIN
SET NOCOUNT ON;
IF EXISTS (SELECT * FROM inserted WHERE Column1 LIKE '%Test%')
BEGIN
DECLARE #msg nvarchar(max)
SET #msg = 'SELECT * FROM Inserted Where Column1 Like ''%Test%'''
--// CHANGE THE VALUE FOR #recipients
EXEC msdb.dbo.sp_send_dbmail
#recipients=N'email#email.co.uk',
#body= #msg,
#subject = 'Worksheet Error',
#profile_name = 'profilename'
END
END
Your query is in quotes. Take out the single quotes and it will set #msg to the results of that query.
A warning though. It will fail if that query returns more than one result. You should also declare the column.

SQL Server 2008 Trigger which sends email

Does anyone know why this wouldn't work? It's a trigger which checks the value of a field on insert and update and sends an email with the value of an id column from the offending row.
ALTER TRIGGER [dbo].[DB]
ON [dbo].[table]
AFTER INSERT, UPDATE AS
BEGIN
IF EXISTS(SELECT 1 FROM inserted WHERE value = 5)
BEGIN
EXEC msdb.dbo.sp_send_dbmail
#recipients = 'me#derp.com',
#profile_name = 'MailProfile',
#subject = 'DB.dbo.table trigger',
#body = '',
#execute_query_database = 'DB',
#query = 'USE DB SET NOCOUNT ON SELECT id FROM dbo.table WHERE value = 5';
END
END
The problem seems to be the #query in the sp_send_dbmail function. When I manually try triggering it I receive the following error;
No row was updated.
The data in row x was not committed.
Error Source: .Net SqlClient Data Provider.
Error Message: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
Correct the errors and retry or press ESC to cancel the change(s).
When I remove #execute_query_database and #query and add some plain text to the #body var the trigger works and I receive an email.
I've also tried changing the #query value to something really simple e.g. SELECT "Test" as test but this didn't help.
I'm completely new to triggers so if the problem is painfully obvious... apologies :)
You need semi-colons:
#query = 'USE DB; SET NOCOUNT ON; SELECT id FROM dbo.table WHERE value = 5;';

Scheduled job not sending emails

I believe that dbMail is properly set up, I can send an email to myself using it.
But I have a scheduleded job which looks like;
DECLARE #Forename VARCHAR(50)
DECLARE #EmailAddress VARCHAR(50)
DECLARE #subject VARCHAR(500)
DECLARE #emailsubject VARCHAR(500)
Declare #bodypre as varchar(5000)
DECLARE #body VARCHAR(5000)
declare #recipients VARCHAR(5000)
Declare #emailStop as int
declare #replaceApproverName as varchar(20)
declare #link as varchar(100)
declare #replaceNextLine as varchar(20)
declare #profile_name as varchar(50)
declare #bodypost as varchar(5000)
declare #footerMessage as varchar(1000)
set #replaceApproverName ='$Approver'
set #replaceNextLine ='$NextLine'
set #link ='$Link'
DECLARE #NewLineChar AS CHAR(1) = CHAR(13)
select #emailsubject=EmailMessageSubject,
#bodypre = EmailMessageBody,
#emailStop = EmailStop_Flag
from STAS.dbo.MC_STAS_EmailMessage where TimeSheetStatusID = 2
SET #bodypre =Replace(#bodypre ,#link, 'http://liveweb.website.com/stas');
select #footerMessage =EmailMessageBody from STAS.dbo.MC_STAS_EmailMessage where MessageType='Footer'
SET #bodypre += #footerMessage;
SET #bodypre =Replace(#bodypre ,#replaceNextLine, #NewLineChar) ;
DECLARE emailCursor CURSOR FOR
SELECT distinct EmailAddress,Forename from [STAS].[dbo].[NotifictationEmailID_View] vw
OPEN emailCursor FETCH NEXT FROM
emailCursor INTO #EmailAddress,#Forename WHILE ##FETCH_STATUS = 0
BEGIN
if(#emailStop = 1)
set #EmailAddress = 'xxx.xxxx#xxxxx.co.uk'
set #bodypost = Replace(#bodypre,#replaceApproverName,#Forename)
EXEC msdb.dbo.sp_send_dbmail
#profile_name='STAS Alert',
#recipients =#EmailAddress,
#subject=#emailsubject,
#body =#bodypost;
FETCH NEXT FROM emailCursor INTO #EmailAddress,#Forename END
CLOSE emailCursor
DEALLOCATE emailCursor
When I look at the Database mail error log I see this;
The mail could not be sent to the recipients because of the mail server failure. (Sending Mail using Account 1 (2013-09-04T14:03:48). Exception Message: Cannot send mails to mail server. (The operation has timed out.).
Sending Mail using Account 1 . Exception Message: Cannot send mails to mail server. (Failure sending mail.).
Yet the profile 'STAS Alert' is set up and I can send an email using it to myself.
So why is this happening and what should I do to fix it?
Did you check out SQL Server Agent Properties/alert system ?
Mail profile should be enabled and your mail profile should be chosen correctly.

Resources