How to create a string using concat to assign to a variable - sql-server

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'

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

Send email via SQL Server Agent, based on the result of a T-SQL stored procedure

I have a T-SQL stored procedure (which returns a single scalar value called #HourDifference as an output parameter); you can see the execution below:
DECLARE #HourDifference_output TINYINT;
-- I declare a variable to capture the output parameter--
EXEC dbo.sproc_XYZ_Notification
#HourDifference = #HourDifference_output OUTPUT;
SELECT #HourDifference_output AS HourDifferenceCaptured
I have the below requirements:
If HourDifferenceCaptured > 12, I will need to send a email
If HourDifferenceCaptured <= 12, no email needs to be sent; nothing needs to be done.
I need to have two schedules, one at 7 AM, the other at 7 PM in the SQL Server Agent.
Can someone provide the code and guide me through this process?
You could create an SQL Server agent job, with a t-sql step which uses msdb.dbo.sp_send_dbmail for sending an e-mail, when required (please see here, for the stored procedure complete reference).
Try something similar to the following:
DECLARE #HourDifference_output TINYINT;
EXEC dbo.sproc_XYZ_Notification #HourDifference_output OUTPUT;
-- SELECT #HourDifference_output AS HourDifferenceCaptured
IF #HourDifference_output > 12
BEGIN
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'db_mail_profile_i_have_already_created',
#recipients = 'intended-recipients#yourorganization.com',
#body = 'Too many hours difference.',
#subject = 'Automated Message' ;
END
You must have already configured a database mail account, a database mail profile and granted appropriate access to the user running the job step. The second link also contains sample scripts for creating a database mail account and profile, adding the account to the profile and granting access appropriately (I personally prefer to configure database mail via the SSMS db mail wizard).
A decision to be made is whether to create a public or a private profile. You can find more information about the differences here.
Finally, it is, in my opinion, good practice to notify an administrator (via SQL Server Agent build-in mechanisms) when a job / step fails.
USE <database_name>
GO
DECLARE #subject NVARCHAR(max) = 'Email subject'
, #body NVARCHAR(MAX)
DECLARE #HourDifference_output TINYINT;
EXEC dbo.sproc_XYZ_Notification #HourDifference = #HourDifference_output OUTPUT;
SELECT #HourDifference_output AS HourDifferenceCaptured
IF (#HourDifference_output> 12)
BEGIN
SET #body = '<!DOCTYPE html>
<html>
<body>
<body style="color:black; font-family:Times New Roman; font-size:14x"> .......... body text ......... </body>
<body style="color:SlateGray; font-family:Times New Roman; font-size:14px;line-height: 1;"> ------------------------------------------------------------------' + '
<body style="color:SlateGray; font-family:Times New Roman; font-size:14px;line-height: 1;"> ------------------------------------------------------------------' + '
</body>
</HTML>'
EXEC msdb.dbo.sp_send_dbmail #profile_name = 'Profile name'
, #recipients = 'distibution email'
, #body = #body
, #body_format = 'HTML'
, #subject = #subject
END
GO

How do you send email with TSQL using a Agent Operator instead of an email address?

I have some custom audit processes that send emails with sp_send_mail. I discovered recently that testing was sending out emails to everybody because the recipient address was hard coded as a variable value. I'd rather use an Operator so I don't have to alter code moving from one environment to the next. I've googled but this doesn't seem to be a thing unless I'm just using the wrong key words.
What is the proper #recipients value to use an Operator or should I be using a different proc all together?
You're definitely on the right track but you just need to retrieve the email address of the operator based on the name of the operator like this:
DECLARE #OperatorName sysname = N'OnCallDBAs';
DECLARE #OperatorEmailAddress nvarchar(100)
= (SELECT email_address
FROM msdb.dbo.sysoperators
WHERE [name] = #OperatorName);
IF #OperatorEmailAddress IS NOT NULL
BEGIN
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'Adventure Works Administrator',
#recipients = #OperatorEmailAddress,
#body = 'The stored procedure finished successfully.',
#subject = 'Automated Success Message';
END;
Hope that helps.

How to send an email to multiple recipients ?

I have a stored procedure which sent emails to few recipients. In this I want to send to two differet recipients using #copy_recipients. But I get a syntax error. How to make this work?
stored procedure code
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'mail',
#recipients = #Mail1,
#copy_recipients = #Mail2;#Mail3,
#body =#body ,
#subject =#subject
You need to add ; (semicolon) between e-mail addresses using string concatenation:
DECLARE #copy_to varchar(max)= #Mail2+';'+#Mail3
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'mail',
#recipients = #Mail1,
#copy_recipients = #copy_to,
#body =#body ,
#subject =#subject
You can read MSDN article here
[ #recipients= ] 'recipients'
Is a semicolon-delimited list of e-mail
addresses to send the message to. The recipients list is of type
varchar(max). Although this parameter is optional, at least one of
#recipients, #copy_recipients, or #blind_copy_recipients must be
specified, or sp_send_dbmail returns an error.
[ #copy_recipients= ] 'copy_recipients'
Is a semicolon-delimited list
of e-mail addresses to carbon copy the message to. The copy recipients
list is of type varchar(max). Although this parameter is optional, at
least one of #recipients, #copy_recipients, or #blind_copy_recipients
must be specified, or sp_send_dbmail returns an error.

sqlcmd library error in sp_send_dbmail

I am using sp_send_dbmail to send an email containing entries in table Persons. It throws following error -
Failed to initialize sqlcmd library with error number -2147467259.
My query is below -
declare #q varchar(max)
SET #q='SELECT FirstName,LastName FROM dw_extract.dbo.Persons'
USE msdb
EXEC sp_send_dbmail
#profile_name = 'profile_name',
#recipients = 'abc#xyz.com',
#subject = 'T-SQL Query Result',
#body = 'The result from SELECT is appended below',
#execute_query_database = 'dw_extract',
#query = #q
I did some research and found that few people who faced such problem could get rid of it by explicitly stating column names and database of the table used. I did that but still it continues to throw the error.

Resources