SQL Server : trying to send email using sp_send_dbmail - sql-server

I'm trying to send attached file from query result using sp_send_dbmail
This is my code:
declare #q nvarchar(max)
select #q = 'select
case when s.mantype = ''99'' then ''Pre-sales''
when s.mantype = ''44'' then ''idk''
when s.mantype = ''77'' then ''Van sales''
when s.mantype = ''33'' then ''Delivery Person''
when s.mantype = ''55'' then ''Manager''
end ''mantype''
from man s '
begin
select #sub = 'Fire a Test ' + cast(convert(date,getdate()) as nvarchar)
EXEC msdb.dbo.sp_send_dbmail
#recipients = 'my#email.com',
#profile_name = 'Profileone',
#subject = #sub,
#body ='TEST' ,
#body_format = 'TEXT',
#query_result_header = 1 ,
#query = #q,
#attach_query_result_as_file = 1,
#query_attachment_filename= 'Report.cvs';
end
but I'm getting an error :
Failed to initialize sqlcmd library with error number -2147467259
Note: when I remove the case in the query and select the column mantype, it runs, but when I add the case again, I get the above error.

It's been a while, I solved this issue by creating a view with the desired query.

Related

Failed to initialize sqlcmd library with error number -2147467259 with a group by and count

Failed to initialize sqlcmd library with error number -2147467259. When I remove the count and group by the query works perfectly. I add the count and group by I get the error above.
'''
DECLARE #sub VARCHAR(100);
DECLARE #qry VARCHAR(1000);
DECLARE #msg VARCHAR(250);
DECLARE #query_ath NVARCHAR(1000);
DECLARE #query_attachment_filename NVARCHAR(1000);
DECLARE #tab char(1) = CHAR(9);
SELECT #sub = 'Daily Absence Report';
SELECT #msg = 'Please refer to the attached spread sheet for the report.'
SELECT #query_ath = 'select a.SCS_STUDENT,
concat(d.FIRST_NAME,'' '',d.LAST_NAME) as Student_Name,
c.STA_OTHER_COHORT_GROUPS,
b.STC_COURSE_NAME,
b.STUDENT_ACAD_CRED_ID,
e.SCS_ABSENT_DATES,
count(case e.SCS_ATTENDANCE_TYPES when ''A'' then 1 end) as
Number_of_Absences
from STUDENT_COURSE_SEC a, STUDENT_ACAD_CRED b, STA_OTHER_COHORTS c, PERSON
d, SCS_ATTENDANCE e
where a.SCS_STUDENT_ACAD_CRED = b.STUDENT_ACAD_CRED_ID
and b.STC_REPORTING_TERM = ''2019FA''
and b.STC_PERSON_ID = left(c.STUDENT_ACAD_LEVELS_ID, 7)
and b.STC_PERSON_ID = d.ID
and c.STA_OTHER_COHORT_GROUPS like ''AT%''
and c.STA_OTHER_COHORT_GROUPS <> ''ATCHR''
and a.STUDENT_COURSE_SEC_ID = e.STUDENT_COURSE_SEC_ID
and e.SCS_ATTENDANCE_TYPES = ''A''
and CONVERT(date, getdate()) = e.SCS_ABSENT_DATES
group by a.SCS_STUDENT,
concat(d.FIRST_NAME,'' '',d.LAST_NAME),
c.STA_OTHER_COHORT_GROUPS,
b.STC_COURSE_NAME,
b.STUDENT_ACAD_CRED_ID,
e.SCS_ABSENT_DATES';
SELECT #query_attachment_filename = 'ath_absences.csv';
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'elearning no shows',
#recipients = 'email', --'ajenkins#eastms.edu',
#copy_recipients = 'rboles#eastms.edu',
#body = #msg,
#subject = #sub,
#execute_query_database = 'db_server',
#query = #query_ath,
#query_attachment_filename = 'ath_absences.csv',
#attach_query_result_as_file = 1,
#query_result_header = 1,
#query_result_width = 256,
#query_result_separator=#tab,
#query_result_no_padding = 1;
'''
As per our discussion in the comments, please increase the number of characters for #query_ath.

SQL query results to mail- Receiving Error formatting query, probably invalid parameters error

I am trying to send the invalid codes to mail. However when I execute the job for stored procedure, it completed fine and did not send any email. When I execute the query alone, I am getting the results. Did I miss any configuration setup?
CREATE PROCEDURE sp_Send_Email_Invalid_code
#MONTH AS int = 0
AS
BEGIN
DECLARE #Email_Subject AS nvarchar(250) = 'Codes Missing in master table';
DECLARE #Email_Receipients_To AS nvarchar(max) = 'xxx.yyy.com';
DECLARE #IsUseEmailConfig AS bit = 1;
DECLARE #Email_Category AS nvarchar(250);
SET #IsUseEmailConfig = 0
SET #Email_Category = 'Codes Missing in master table'
SELECT DISTINCT CODE
INTO #temp_1
FROM tblRegCode nolock
SELECT
*
FROM
#temp_1
DECLARE #Query nvarchar(max);
SET #Query = 'SELECT * FROM #temp_1';
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'psmEmailer',
#recipients = 'xxx.yyy.com',
#query = #Query,
#subject = 'Missing codes',
#attach_query_result_as_file = 1 ;
DROP TABLE #temp_1;
END
My SQL Server agent job is
DECLARE #MONTH AS int = 0
DECLARE #dt datetime = GETDATE()
SET #MONTH = DATEPART(mm, DATEADD(mm, -1, #dt))
EXEC sp_Send_Email_Invalid_code #MONTH
This is difficult to answer because there isn't anything obvious in the code above that is coursing the issue. Therefore the problem must be else where. My thoughts are 1) your query result set isn't returning anything. 2) Your email config is correct meaning the email can't be sent.
For number 1, we can't resolve this without checking your data, so moving on.
For number 2, try sending a simple email from the SQL instance using the send mail procedure in isolation. Like this:
EXEC msdb.dbo.sp_send_dbmail
#recipients = 'you#somewhere.com',
#subject = 'Send Mail Test',
#body = 'Testing',
#body_format = 'HTML';
Then is you don't receive an email check the failure logs in MSDB with the following query.
USE [msdb]
GO
SELECT
l.[description] AS 'Error failure',
f.[recipients],
f.[subject],
f.[sent_date],
f.[body],
f.[body_format]
FROM
[dbo].sysmail_faileditems f
JOIN [dbo].sysmail_event_log l
ON f.[mailitem_id] = l.[mailitem_id]
ORDER BY
f.[sent_date] DESC
If you do receive the test email I'd suggest the problem is with your query results that your trying to attach.
Just another thought. You may also need to use the param #execute_query_database and #query_attachment_filename.
Check https://msdn.microsoft.com/en-us/library/ms190307.aspx for details.
So, you can make from your SP just this:
CREATE PROCEDURE sp_Send_Email_Invalid_code
#MONTH AS int
AS
BEGIN
DECLARE #Query nvarchar(max) = 'SELECT [CODE ] FROM tblRegCode nolock';
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'psmEmailer',
#recipients = 'xxx.yyy.com',
#query = #Query,
#subject = 'Codes Missing in master table',
#attach_query_result_as_file = 1 ;
END
GO
In the SP you are not using #MONTH, why?
Try to add WITH EXECUTE AS OWNER in your SP, and run it via job.

SQL Server: emailing the results of a dynamic SQL query

I am trying to build a loop with a cursor in order to send a list of backorders to clients having such backorders.
The WHILE loop with the cursor is ok, and I am fetching the current #idClient and #email correctly, but I don't know how to have the query filtered on #idClient.
Here is the (non working) statement I made so far:
exec msdb..sp_send_dbmail #profile_name='sql_mail_lu',
#recipients = #email,
#subject = 'Your backorders',
#body = 'Please find in attachment the list of your items in backorder.',
#execute_query_database = 'ERPSQL',
#query = '
SELECT TOP 100
NoDoc, Refer Product, Comm Ordered, isnull(Livr, 0) Delivered, BackOrder, VRef
FROM erpSQL.dbo.vwBoClients
WHERE idclient = ' + #idClient' ,
#attach_query_result_as_file = 1,
#query_attachment_filename ='backorders.txt'
My question is: how should I formulate the #query = part to make it work ?
You need to escape those single quotations:
exec msdb..sp_send_dbmail #profile_name='sql_mail_lu',
#recipients=#email,
#subject='Your backorders',
#body= 'Please find in attachment the list of your items in backorder.',
#execute_query_database = 'ERPSQL',
#query = '
SELECT TOP 100
NoDoc, Refer Product, Comm Ordered, isnull(Livr, 0) Delivered, BackOrder, VRef
FROM erpSQL.dbo.vwBoClients
WHERE idclient = ''' + #idClient + ''' ,
#attach_query_result_as_file = 1,
#query_attachment_filename =''backorders.txt'''

SQL Server msdb.dbo.sp_send_dbmail

I want to publish some query results in the e-mail in a structured format. I'm using the #body_format as 'HTML'.
I want to do like:
Declare #processed_rows int
declare #Sourcetype varchar(100)
select #sourcetype = (some SQL query)
select #processed_rows = (some SQL query)
exec msdb.dbo.sp_send_dbmail
#body='some HTML' ,
#subject = 'IGD-DEVELOPMENT SERVER UPDATED',
#profile_name = 'IGDMail',
#recipients = ' abhisheks#exzeo.com
When I'm executing msdb.dbo.sp_send_dbmail, I want to pass these variables in the #body argument of stored procedure and use them in the final email, please help to achieve this?
You'll need to declare another variable to hold your HTML code:
DECLARE #HTML NVARCHAR(MAX)
SET #HTML = 'SOME HTML HERE' + CAST(PROCESSED_ROWS AS VARCHAR) + 'SOME MORE HTML' + #SOURCETYPE
EXEC MSDB.DBO.SP_SEND_DBMAIL
#BODY = #HTML
, #BODY_FORMAT = 'HTML'
ETC.....
You get the idea...

adding dynamic content within body of an email (database mail) with sp_send_dbmail

Is there a way I can add the time in the following query as the body of my email :
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'TEST_DEV',
#recipients = 'xxx#gmail.com',
#query = ' select
Percentage = CONVERT(DECIMAL(10,1),100 - (CAST(COUNT(DISTINCT case when PD.Exception != ' ' then PD.Id END) as float)/CAST(COUNT(PD.Id) as float)*100))
from
DataBaseName.dbo.Product P INNER JOIN DataBaseName.dbo.LogProduct PD
ON P.LogId = PD.LogId
WHERE
ResponseTime < GETDATE() and RequestTime > DATEADD(MINUTE, -150, GETDATE())
' ,
#subject = 'Test',
#body = 'Please check the attached file for Providers with Many unsuccessful calls between the time xx an yy',
#attach_query_result_as_file = 1 ;
In the current line
#body = 'Please check the attached file for info on calls between the time xx an yy',
I would like to add GetDate() in place of xx and DATEADD(MINUTE, -150, GETDATE()) in place of yy ?
is it possible ?
declare #body nvarchar(max)
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'DEV',
#recipients = 'xxx#gmail.com',
#query = 'exec Database.dbo.spTest' ,
#subject = 'Test',
select #body = 'Please check the attached file for info on calls between the time ........................',
#attach_query_result_as_file = 1 ;
Would you want me to do something like this ?
You can declare your #body variable before the EXEC statement and make it any string that you'd like.
Edit:
I updated this to be more verbose. I dont have sp_send_dbmail configed anywhere to test, but I think it should work fine. I created a string variable called #bodyMsg, set it to the string you want before the stored procedure call, then gave the value over to the #body variable in sp_send_dbmail.
declare #bodyMsg nvarchar(max)
select #bodyMsg = 'Please check the attached file for info on calls between the time ' + convert(varchar,GETDATE()) + ' and ' + convert(varchar,DATEADD(mm, -150, getdate())) + '.'
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'TEST_DEV',
#recipients = 'xxx#gmail.com',
#query = ' select
Percentage = CONVERT(DECIMAL(10,1),100 - (CAST(COUNT(DISTINCT case when PD.Exception != ' ' then PD.Id END) as float)/CAST(COUNT(PD.Id) as float)*100))
from
DataBaseName.dbo.Product P INNER JOIN DataBaseName.dbo.LogProduct PD
ON P.LogId = PD.LogId
WHERE
ResponseTime < GETDATE() and RequestTime > DATEADD(MINUTE, -150, GETDATE())
' ,
#subject = 'Test',
#body = #bodyMsg,
#attach_query_result_as_file = 1 ;
Then just pass the #body variable to the sp_send_dbmail stored procedure. Different datetime formats can be found here: http://technet.microsoft.com/en-us/library/ms187928.aspx

Resources