SQL Server: emailing the results of a dynamic SQL query - sql-server

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

Related

SQL Server : trying to send email using sp_send_dbmail

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.

How to avoid the column name with lines displaying while calling sp_send_dbmail?

I'm new to stored procedure. I've tried to mail by reading a table and did the below query
create procedure mailtouser
as
declare #data varchar(max),
#user varchar(max)
as
set #data='set nocount on;select col_name from tbl_name where id=1;set nocount off;'
set #user='user#example.com'
set #query=
exec sp_send_dbmail
#profile_name = 'profile',
#recipients = #user,
#subject = 'automail',
#execute_query_database = 'database',
#query = #data;
end
end
exec mailtouser
go
while executing this script, i'm getting mail
as
col_name
------------------------------------------------------------------------------------------------------------
datas.
how to avoid this col_name and lines. i want that data alone in mail.
First, are you actually naming a database as [database]? It should be something like [AdventureWorks2012].
Second, the query will execute and return results. You do not need #execute_query_database if you use three part notation [AdventureWorks2012].[Person].[Address].
Third, there are other parameters that go along with this option. Check them out.
#query_result_header
#query_result_width
#query_result_separator
#exclude_query_output
On the other hand, if you want to take full control, change the body format to HTML.
Run the query inside an SET statement to format the data the way you want.
-- Send with embedded html table containing query data
DECLARE #VAR_HTML NVARCHAR(MAX) ;
SET #VAR_HTML =
N'<h1>Work Order Report<h1>' +
N'<table border="1">' +
N'<tbody><tr><th>Work Order ID</th><th>Product ID</th>' +
N'<th>Name</th><th>Order Qty</th><th>Due Date</th>' +
N'<th>Expected Revenue</th></tr>' +
CAST ( ( SELECT td = wo.WorkOrderID, '',
td = p.ProductID, '',
td = p.Name, '',
td = wo.OrderQty, '',
td = wo.DueDate, '',
td = (p.ListPrice - p.StandardCost) * wo.OrderQty
FROM AdventureWorks2008R2.Production.WorkOrder as wo
JOIN AdventureWorks2008R2.Production.Product AS p
ON wo.ProductID = p.ProductID
WHERE DueDate > '2006-04-30'
AND DATEDIFF(dd, '2006-04-30', DueDate) < 2
ORDER BY DueDate ASC,
(p.ListPrice - p.StandardCost) * wo.OrderQty DESC
FOR XML PATH('tr'), TYPE
) AS NVARCHAR(MAX) ) +
N'</tbody></table>'
EXEC msdb.dbo.sp_send_dbmail
#recipients='john#craftydba.com',
#subject = 'Work Order List',
#body = #VAR_HTML,
#body_format = 'HTML' ;
Sincerely
J

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

How to arrange the fields in notepad which is coming from db_send_email

I have the notepad with the expected results...But the fields are not arranged properly.One column is coming in one line and another in another like.Its not looking good.I heard like we can set the column width for the result set.Please help me with the syntax and an example.
Assuming that you mean sp_send_dbmail procedure to send database mail but not db_send_email. In such case you can control your output format in the following way.
1. Set width of output line to fixed value.
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'Mailer',
#recipients = 'undisclosed',
#query = 'SELECT field_int
, field_varchar_50
, field_varchar_250
FROM mytable' ,
#query_result_no_padding = 0,
#query_result_width = 400 ;
Selected width should be greater than sum of lengthes of all fields in the query, e.g. #query_result_width = 400. However, this will produce too wide lines especially in case varchar(50) or varchar(250) fields have many padding spaces.
2. Truncate fields.
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'Mailer',
#recipients = 'undisclosed',
#query = 'SELECT field_int
, LEFT(field_varchar_50, 25)
, LEFT(field_varchar_250, 25)
FROM mytable' ,
#query_result_no_padding = 0 ;
This will produce output where varchar(50) or varchar(250) will be truncated to 25 symbols. Of course, you can use any appropriate different value.
3. Adjust field lengths.
Just add field lengths calculation and produce output with exact width.
DECLARE #iField_varchar_250_length
SELECT #iField_varchar_250_length = MAX(LEN(field_varchar_250)) FROM mytable
DECLARE #sQuery VARCHAR(200)
SELECT #sQuery = 'SELECT field_int
, LEFT(field_varchar_50, 25)
, LEFT(field_varchar_250, ' + CAST(#iField_varchar_250_length AS VARCHAR(10)) + ')
FROM mytable' ,
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'Mailer',
#recipients = 'undisclosed',
#query = #sQuery,
#query_result_no_padding = 0 ;

Pass Query Results to a csv file and Send it as mail using SQL Server 2005

I have two tasks and since I am new to it, I need some help/advice from the masters.
What I need to do is send the result of q select query to a csv file which can have delimeter as comma or tab and then send this file as mail to a particular receipient.
Hoping for some great advice
Try something like that:
DECLARE #cvs nvarchar(MAX)
DECLARE #separator nvarchar(1)
SET #cvs = N''
SET #separator = ','
SELECT TOP 10
#cvs = #cvs + CAST(int_column AS nvarchar) + #separator + nvarchar_column + #separator + CAST(datetime AS nvarchar) + CHAR(13)
FROM
data_table WITH (NOLOCK)
SELECT #cvs
PRINT #cvs
EXEC msdb.dbo.sp_send_dbmail
#recipients = #mail_recipients,
#profile_name = 'SO',
#subject = #mail_subject,
#body = #cvs
Use COALESCE to avoid NULL values, cast columns to nvarchar type if needed.

Resources