Using a variable as #Subject with sp_send_dbmail - sql

I got the following Code which runs more or less smoothly.
DECLARE #MyId char(4),#MyResult varchar(max), #MySubject varchar(max);
SET #ID = 5;
SET #MyId = #ID;
SELECT #MyResult = SQL_Script FROM Table1 WHERE ID = + #MyId;
SELECT #MySubject = Subject FROM Table1 WHERE ID = + #MyId;
EXEC msdb.dbo.sp_send_dbmail
#profile_name='Operator',
#recipients= 'test#mail.com',
#subject= #MySubject,
#query_result_separator = ' ',
#query_result_no_padding= 1,
#body= 'test',
#query_attachment_filename = 'Test.csv',
#query= #MyResult ,
#mailitem_id='1',
#attach_query_result_as_file = 1
END
The result of the Query which is store in #MyResult works just fine, but when I store a String in #MySubject I won't get a Mail.
If I write:
#subject= #MySubject, <-- Doesn't work (The String is not 'NULL')
#subject = 'test', <-- works
I have to save a String, which is located in Table1, into #MySubject and then use it as Subject for my Mail.
Sadly it has to be dynamic so I somehow have to get this to work.

using variable is not the issue.
Probably, this
#MySubject varchar(max)
the #subject parameter supposed to be nvarchar(255)
what is the value of #MySubject ? is it readable text ?

Spaces seem to be the problem:
SET #Subj = 'Test Subject' <- does not work
SET #Subj = 'Test_Subject' <- works

Related

SQL sending email with data

I am trying to send a table via email in a table like shape. What I mean is to style nicely the text that I am receiving in email, because now it looks ugly, not like a table. Any help would be much appreciated.
ALTER PROCEDURE [dbo].[testEmail]
AS
BEGIN
DECLARE #SubjectText VARCHAR(100) = 'Day ' + CONVERT(VARCHAR,(CONVERT(DATE,GETDATE())))
DECLARE #tab char(1) = CHAR(9);
BEGIN
EXEC msdb.dbo.sp_send_dbmail
#query = 'SELECT IDDruzyny, nazwa FROM TEST.dbo.Druzyna',
#body = '
<html>
<body>
<br/><b><font color=red>Hiho</font></b>
</body>
</html>
',
#Body_format = 'HTML',
#subject = #SubjectText,
#profile_name = 'SIT',
#recipients = 'safemail#onet.eu',
#attach_query_result_as_file = 0,
#query_result_separator = #tab,
#query_result_header = 1
END
END

SSIS Error: Unable to retrieve destination column descriptions from the parameters of the SQL command

I am getting an error :
[Load updated records to Table_vwAs_FixedIdentifier [85]] Error: Unable to retrieve destination column descriptions from the parameters of the SQL command.
when I execute the SSIS task in the image. It fails on the lower left "Load updated records to Table_vwAs.." oleDb update task. It has the following sql statement and also has a trigger also shown below. I have not been able to identify the cause of this issue till now. When I disabled the trigger, the task ran successfully. Any help will be eye-opening.
UPDATE
[dbo].[Sec]
SET
[SecID]=?
,[SECURITY_NAME]=?
,[SECURITY_SECTYPE_ID]=?
,[SECURITY_EXCHANGE_ID]=?
WHERE
[MasterID]=?
Trigger code is as follows:
alter trigger [dbo].[TrTable_Fixed_AFTERUPDATE] on [dbo].[Sec]
after insert ,update
as
set NOCOUNT on
declare #DBMailDistributionListId varchar(50)
declare #ProfileName varchar(max)
declare #Recipients varchar(max)
declare #CopyRecipients varchar(max)
declare #BlindCopyRecipients varchar(max)
set #DBMailDistributionListId = 'Crossadyne1'
set #ProfileName = SharedCode.dbo.FnGetDBMailDistributionListProfileName(#DBMailDistributionListId)
set #Recipients = SharedCode.dbo.FnGetDBMailDistributionListRecipients(#DBMailDistributionListId)
set #CopyRecipients = SharedCode.dbo.FnGetDBMailDistributionListCopyRecipients(#DBMailDistributionListId)
set #BlindCopyRecipients = SharedCode.dbo.FnGetDBMailDistributionListBlindCopyRecipients(#DBMailDistributionListId)
declare #Subject varchar(max)
declare #Body varchar(max)
set #Body = ''
select distinct #Body = #Body + 'Master Sec ID: ' + convert(nvarchar(50) ,i.MasterId) + char(13) + char(10)
+ 'New Legal Entity ID: ' + convert(nvarchar(50) ,i.[INTERNAL_SECURITY_LEGALENTITY_ID])
from INSERTED i
inner join DELETED d
on i.MasterId = d.MasterId
where i.[INTERNAL_SECURITY_LEGALENTITY_ID] <> d.[INTERNAL_SECURITY_LEGALENTITY_ID]
and i.Security_Change_Date = i.LegalEntityChangeDate
and i.LegalEntityChangedBy not in (2 ,5)
if (#Body <> '')
begin
set #Subject = 'WARNING: Crossadyne Security Legal Entity changed'
exec msdb.dbo.sp_send_dbmail
#profile_name = #ProfileName
, #recipients = #Recipients
, #copy_recipients = #CopyRecipients
, #blind_copy_recipients = #BlindCopyRecipients
, #subject = #Subject
, #body = #Body
end
set #DBMailDistributionListId = 'test'
set #ProfileName = SharedCode.dbo.FnGetDBMailDistributionListProfileName(#DBMailDistributionListId)
set #Recipients = SharedCode.dbo.FnGetDBMailDistributionListRecipients(#DBMailDistributionListId)
set #CopyRecipients = SharedCode.dbo.FnGetDBMailDistributionListCopyRecipients(#DBMailDistributionListId)
set #BlindCopyRecipients = SharedCode.dbo.FnGetDBMailDistributionListBlindCopyRecipients(#DBMailDistributionListId)
set #Body = ''
select distinct #Body = #Body + 'Master ID: ' + convert(nvarchar(50) ,i.MasterId) + char(13) + char(10)
+ 'Previous Legal Entity ID: ' + convert(nvarchar(50) ,d.[INTERNAL_SECURITY_LEGALENTITY_ID])
from INSERTED i
inner join DELETED d
on i.MasterId = d.MasterId
where i.[INTERNAL_SECURITY_ID] <> d.[INTERNAL_SECURITY_LEGALENTITY_ID]
if (#Body <> '')
begin
set #Subject = 'WARNING: Crossadyne Security Legal Entity changed'
exec msdb.dbo.sp_send_dbmail
#profile_name = #ProfileName
, #recipients = #Recipients
, #copy_recipients = #CopyRecipients
, #blind_copy_recipients = #BlindCopyRecipients
, #subject = #Subject
, #body = #Body
end
set NOCOUNT off
The issue was being caused due to
exec msdb.dbo.sp_send_dbmail
in the trigger code, because it is not configured on the QA server. Resolved after I commented those lines.

db sendmail in SQL still showing rows affected after params turned off

I'm sending results through an XML variable formatted with CSS and HTML in the body of an email. I have everything exactly the way I want it and it's still showing the garbled text query at the bottom of the HTML email. I have the #exclude_query_output turned off as well as SET NOCOUNT ON; in the actual #query paramater.
I've even tried to use NOCOUNT ON in the XML part of the SELECT statement and it's not working. Everything else seems to be working great but the text query still shows at the bottom of the email.
I'm pasting partial code due to security but here is some of it:
DECLARE #xml NVARCHAR(MAX)
declare #variousothervariableshere, like #subject1
SET #subject1 = 'Send Statistics for '+ #datenamemonth + ' ' + #datenameyear
set nocount on;
SET #xml = CAST(( SELECT
'left' as [td/#align], Task AS 'td','', 'center' as [td/#align], NumofRecords AS 'td',''
FROM [mytablehere] FOR XML PATH('tr'), ELEMENTS ) AS NVARCHAR(MAX))
set #HTMLBody = '<html><head>'
+ '<style>'
+ 'th {border: solid blue 1px;padding-left:5px;padding-right:5px;padding-top:1px;padding-bottom:1px;font-size:11pt;} '
+ 'td {border: solid blue 1px;padding-left:5px;padding-right:5px;padding-top:1px;padding-bottom:1px;font-size:11pt;} '
+ '</style>'
+ '</head>'
+ '<body>'
+ '<p>'
+ '<table border="1">'
+ '<tr>'
+ '<th style="color:#fff000;">Num of Records</th>'
+ '</tr>'
set #HTMLBody = #HTMLBody + #xml + '</table></body></html>'+'<font face="Verdana" size="2" color="#333333"><p><br />Thanks,<br />My name here<p><p>'
EXEC msdb.dbo.sp_send_dbmail
#exclude_query_output = 1,
#query_result_header = 0,
#profile_name = 'myprofilename',
#recipients = 'myemail#email.com',
#subject = #subject1,
#query = 'SET NOCOUNT ON; select * from [mytablehere]; SET NOCOUNT OFF;',
#body_format = 'HTML',
#body = #htmlbody
--end
Here is what is at the bottom of the email:
Files Imported 0 Total Clean Records Imported 0 Emails Successfully Sent 0 Emails Queued or Retried to Send 0 Emails Failed 0 Number of Emails Exported for Manual Send due to No Data 0
This the exact text that is the HTML formatted table I have right above it. It looks great in the table but I'm getting these results which is the exact query in text and it shouldn't be there because it's formatted in the table above.
Any suggestions would be awesome. Also this is not the full HTML but you get the idea.
Remove the #query parameter from the dbo.sp_send_dbmail call.
EXEC msdb.dbo.sp_send_dbmail
#exclude_query_output = 1,
#query_result_header = 0,
#profile_name = 'myprofilename',
#recipients = 'myemail#email.com',
#subject = #subject1,
#body_format = 'HTML',
#body = #htmlbody

using select in #recipients in sp_send_dbmail

I am using a sp_send_dbmail in a procedure. I execute it 4 times with different countries.
exec pr_drop_out_addresses #country='NO'
exec pr_drop_out_addresses #country='SE'
exec pr_drop_out_addresses #country='FI'
exec pr_drop_out_addresses #country='DK'
For each exec I would like to send the mail to set og receipients. They are different for each country. I try to solve it with a declare #recipients, but I get problems with the quotes. The code is like this. Any suggestions how to bypass the problem?
declare #country varchar (10)
set #country='SE'
declare #recipients nvarchar(500)='''' +select CASE when #country='NO' then 'xxxx#xxx' when #country='SE' then 'yyy#xxxx' END+'''';
declare #subject nvarchar(255) = 'Adresser fra ' + #country;
declare #query_attachment_filename nvarchar(255) = 'Adresser_for_'+#country +'_'+convert(varchar(10),getdate(),121) +'.csv';
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'VNPSQL email',
#recipients = #recipients,
#query = 'SELECT * FROM NSGstatistikk_dev.dbo.test',
#subject = #subject,
#attach_query_result_as_file=1,
#query_attachment_filename = #query_attachment_filename,
#query_result_separator = ';',
#query_result_no_padding = 1;
You are using incorrect syntax:
Use:
SELECT #recipients ='''' + CASE when #country='NO' then 'xxxx#xxx' when #country='SE' then 'yyy#xxxx' END+'''';
also, quotes are not required at all:
SELECT #recipients = CASE when #country='NO' then 'xxxx#xxx' when #country='SE' then 'yyy#xxxx' END;

Stored Procedure sends two emails

EDIT
My previous posting on this subject involved specific transactions within the procedure which are no longer used and the error now only seems to occur in a very specific set of circumstances when I use an invalid user name to our companies email address badname#ourcompany.co.uk
The agent runs a stored procedure every ten minutes to send out emails. If it finds a new record then it sends a mail.
Noticed some strange behavior - if the TO field is correct but the BCC is an invalid email address but uses our valid company domain name (e.g. rubbishPart#ourcompany.co.uk) then the stored procedure sends out two emails to the TO. The domain name needs to be our company's domain name to get this behavior ...if I change the domain to gmail.com then only one mail goes out.
Why is this happening?
How do I change this behavior?
Is the Catch in this procedure redundant?
Here is the procedure:
BEGIN TRY
DECLARE #Exit TINYINT = 0
WHILE #Exit = 0
BEGIN
DECLARE #MailIdFound INT =
(
SELECT CASE
WHEN MIN(EmailId) IS NULL THEN 0
ELSE MIN(EmailId)
END
FROM WH.dbo.EmailQueue
WHERE DateEmailKey IS NULL
)
IF #MailIdFound = 0
BEGIN SET #Exit = 1 END --exit here as
ELSE
BEGIN --send the mail here
DECLARE #DateEmailKey INT
DECLARE #EmailBCC NVARCHAR(1000)
DECLARE #EmailTO NVARCHAR(1000)
DECLARE #EmailCC NVARCHAR(1000)
DECLARE #EmailBody NVARCHAR(MAX)
DECLARE #EmailImportance VARCHAR(6)
DECLARE #EmailSubject NVARCHAR(1000);
WITH myMostUrgentMail_cte
AS
(
SELECT TOP 1
DateEmailKey,
EmailBCC,
EmailTO,
EmailCC,
EmailBody,
EmailImportance,
EmailSubject
FROM WH.dbo.EmailQueue
WHERE EmailId = #MailIdFound
)
SELECT #DateEmailKey = DateEmailKey,
#EmailTO = EmailTO,
#EmailCC = EmailCC,
#EmailBCC = EmailBCC,
#EmailBody = EmailBody,
#EmailSubject = EmailSubject
FROM myMostUrgentMail_cte;
SET #EmailBody = #EmailBody + '<html>

<span style=''font-size:11.0pt;font-family:"Calibri","sans-serif"; color:black''><p><b>blah blah</b></p></span></html>'
EXEC msdb..sp_send_dbmail
#recipients = #EmailTO,
#copy_recipients = #EmailCC,
#blind_copy_recipients = #EmailBCC,
#subject = #EmailSubject,
#Importance = #EmailImportance,
#body_format = 'html',
#body = #EmailBody
UPDATE x
SET x.DateEmailKey = (CONVERT(CHAR(8),GETDATE(),(112))),
x.DateEmailTime = (CONVERT([time](7),left(CONVERT([char](12),GETDATE(),(114)),(8)),(0)))
FROM WH.dbo.EmailQueue x
WHERE x.EmailId = #MailIdFound
END
END
END TRY
BEGIN CATCH
-- handle error here
EXEC msdb..sp_send_dbmail
#recipients = 'ME#ME.com;'
, #subject = 'ERROR OCCURED DURING EMAIL CREATION'
, #body_format = 'html'
, #body = 'ERROR OCCURED'
UPDATE x
SET x.ErrorOccured = 1
FROM WH.dbo.EmailQueue x
WHERE x.EmailId = #MailIdFound
END CATCH;