INSERT Trigger in SQL Server with condition [duplicate] - sql-server

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

Related

SQL Server 2014 INSERT trigger not firing (not sending mail)

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

How can I create an alert in SQL Server?

I have the following structure:
cho_id int
cho_nombre varchar(200)
cho_documento varchar(15)
cho_dirrecion varchar(100)
cho_telefono varchar(15)
cho_fec_vencimiento_lic datetime
cho_categoria int
est_id int
I have a row of datetime type and I want that every time the date approaches send me an alert 15 days before and send me by email.
How can I design this in SQL Server? Does it have to be with stored procedures? Triggers?
Here's a quick shell you can use for a procedure, which you'll then schedule as a job to run daily. You can change the logic of the IF as you seem fit.
create procedure myProc
as
if (select datediff(day,max(cho_fec_vencimiento_lic),getdate()) from SomeTable) = 15
begin
exec msdb.dbo.sp_send_dbmail
#profile_name = null,
#recipients = 'email#domain.org',
#body = 'This is your email alert',
#body_format = 'TEXT',
#subject = 'Alert'
end
go
sp_dend_dbmail reference
Schedule a job reference

How to create a string using concat to assign to a variable

I'm using the sp_send_dbmail stored procedure, and I'm trying to include the result from a query in the body string. I can't seem to get this to work. Any ideas would be much appreciated.
use msdb
go
exec sp_send_dbmail
#profile_name = 'WarehouseEmailer',
#recipients = 'someone#example.com',
#subject = 'Database Mail Test 1',
#Body = 'This is a test email from SQL Server. <br> This should be line 2. <br> The
subject\'s first name is: '+ (select top(1) FirstName from Warehouse.dbo.Subject),
#body_format = 'HTML'
Obviously this example just a simple test, but it is exactly the type of data I'd like to pass to the stored procedure to include in the email body. I look forward to your responses and many thanks for any advice!
Dynamic SQL, or concatenated strings, cannot be passed into the procedures parameters like that.
Try this:
use msdb
go
declare #msgbody nvarchar(1000)
set #msgbody = 'This is a test email from SQL Server.' + char(10) + 'This should be line 2. <br> The
subject''s first name is: '+ (select top(1) FirstName from Warehouse.dbo.Subject)
exec sp_send_dbmail
#profile_name = 'WarehouseEmailer',
#recipients = 'someone#example.com',
#subject = 'Database Mail Test 1',
#Body = #msgbody,
#body_format = 'HTML'

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;';

Resources