sp_sent_email - attachment as grid - sql

I have quite a big problem with a task which should be easy.
I would like to write a procedure that would send query results by mail as an attachment.
My problem is that the format of attachment is in text, not an grid form.
Using code as below:
set #query = 'select 1 as a , 2 as b'
EXEC msdb.dbo.sp_send_dbmail #profile_name = #profilename
, #recipients = #emailto
, #copy_recipients = #recipients
, #Subject = #SubjectTitle
, #body = #body
, #query = #query
, #query_attachment_filename = 'test.csv'
, #attach_query_result_as_file = 1
, #query_result_no_padding = 1
I get on my email .csv file as per below:
a b
- -
1 2
(1 rows affected)
While, I would like to have something in the format which would be recognized by excel. So something like that:
a,b
1,2
Could you please advise?

While I totally agree with #Larnu that SQL is - putting this politely - not the best at this, it can be done with ugly queries like
SELECT CONCAT('a', ',', 'b')
UNION ALL
SELECT CONCAT(CAST(1 AS VARCHAR(5)),',',CAST(2 AS VARCHAR(5)))
Result:
a,b
1,2
It's also possible to coax SQL into creating valid HTML tables, but it's a lot of string manipulation and very brittle.

Related

Export SQL result to csv through sp_send_dbmail

I am trying to create a Job that sends SQL result as a CSV attachment via email.
I manage to do it through the following code:
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'main',
#recipients = 'test#email.com',
#body = 'test',
#query = 'SELECT column1, column2, column3 FROM DB.dbo.Table',
#attach_query_result_as_file = 1,
#query_attachment_filename = 'Test.csv',
#query_result_header = 1,
#query_result_width = 256,
#query_result_separator = ',',
#exclude_query_output = 1,
#append_query_error = 1,
#query_no_truncate = 0,
#query_result_no_padding = 1,
#subject = 'Test';
However, I have 2 problems:
They are all in one column separated by comma instead of 3 columns.
There is an extra row after the column header that contains dashes.
Current CSV File:
Desired CSV File:
Any help will be appreciated :)
Thanks!
So, I just found an answer to my own question.
Apparently, I have to insert a new row in the top of the file containing “sep=,”. This forces Excel to understand that it is a comma delimited file, and ensures that it will open correctly.
You can alter the name of the first column to include this header text. We simply rename “Column1” to “sep=,{CR}{LF}Column1”. Then when dbmail prints out the column headers in the file, the Column1 name will be split on two lines, preceeded by “sep=,”.
Excel treats this first row as an instruction and does not display it, just uses it to make sure it formats the data correctly.
Full Details here: https://www.purplefrogsystems.com/blog/2014/04/excel-doesnt-open-csv-files-correctly-from-sp_send_dbmail/
USE "SET NOCOUNT ON" with two query's to solve this problem.
the first query is the headers.
the second query is the result.
example:
#query = 'SET NOCOUNT ON
SELECT ''COLUMN NAME 1'', ''COLUMN NAME 2'', ''COLUMN NAME3''
SELECT P.PRODUCT, P.PRICE, P.TYPE
FROM PRODUCTS P'

CSV file from the SQL Server is out of format

I am new to SQL Server and trying to send a CSV file as an email attachment to business users. Unfortunately, the file received is totally out of format. I have the following code and the table is from SAP B1. What would be the best way to resolve this?
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'profile name',
#recipients = 'recipent name',
#subject = 'Test',
#query = 'select slpcode, slpname, memo, commission from dbo.OSLP ',
#attach_query_result_as_file = 1,
#query_attachment_filename = 'Results.csv',
#query_result_separator = ',',
#query_result_width = 32767,
#query_result_header = 1,
#append_query_error = 1,
#query_no_truncate = 0
edit: Ideally, the data should be shown in only 4 columns as I have queried only 4 columns but instead this information is spread across columns A:N
Any help would be greatly appreciated.
The sample data in the table looks as follows:
Sample Data Link
and the result from my code shows up as follows:
Final Result Link
Thanks,

SQL HTML email showing blank when one table has no results

The following code sends 2 diferent tables based on an sql query through the function sp_send_dbmail , the catch is , if both tables return results , the email shows up without any problem , perfectly. If one of the tables has NO results, the email comes up completly blank.
How can i fix this?
Thanks
declare #tableHTML NVARCHAR(MAX);
set #tableHTML = N'Este foi o resultado de Faturas Emitidas: <br><br><table border ="1">' +
N'<tr><th>Documento</th></tr>' +
cast (( select td = cc.tx
from cc
for xml path ('tr'),type) as nvarchar(max)) +
N' </table><table border ="1"><tr><th>Valor Total Vencido</th></tr>'
+
cast (( select td = fx.tc
from fx
for xml path ('tr'),type) as nvarchar(max)) +
N'</table>';
EXEC sp_send_dbmail
#profile_name ='xx_SqlMail',
#recipients ='ccccc#hotmail.com',
#subject ='Resumo',
#body =#tableHTML,
#body_format='HTML';
I would suspect that part of your query is returning a NULL value. Concatenating any value with a NULL will always result in NULL.
SELECT 'A' + NULL + 'B' will return NULL.
As you are doing multiple concatenations it would mean that if any value is NULL then #tableHTML will be NULL. Try wrapping your selects in an ISNULL().
select ISNULL(td, '') = cc.tx ...
Any table in your concatenation that returns a NULL will make the entire concatenation NULL.
To resolve this, just wrap each section that could potentially be NULL with an ISNULL().
I had a similar issue where I was running two separate queries and building two tables that I wanted to include in the body of the email. One would occasionally return no values and the email would come back blank. Using ISNULL fixed it for me.
See the code below for an example of what I did:
set #tablesHTML = **ISNULL**(#tableOneHTML,'NO RESULTS')
+ **ISNULL**(#tableTwoHTML,'NO RESULTS')
exec XXXXXX.[XXX].[sp_send_dbmail]
#profile_name='Mail'
,#recipients = #EmailRecipients
,#copy_recipients= #EmailCopyRecipients
,#subject = 'Email Subject Here'
,#body = #tablesHTML
,#body_format = 'HTML'

How to send string result as attachment in stored procedure sql server

i need to send a attachment to user, so i found query as attachment is possible but , my requirement is to send the SP result #V_Message variable as attachment within #attach_query_result_as_file , can any one help me in this issue
I don't have enough reputation points and cannot leave comments, hence it is here:
If all you need to send an email with well-formed attachments, then you should look into
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'whateverDefaultMailProfile',
#recipients = 'user#domain.com',
#subject = 'Email from SQL Server',
#body = 'Enter text here or use a #text var for body.',
#query= 'exec your_stored_procedure'
#file_attachments = 'C:\filename.ext'
your_stored_procedure should dump the output to c:\filename.ext file. You can attach multiple files to multiple recipients from within a single invocation of sp_send_dbmail. Hope this helps.
Yes. you can send attachment via email using (sp_send_dbmail stored proc)
Refer Example below. Hope this helps
EXEC sp_send_dbmail #profile_name='default',
#recipients='dev#null.com',
#subject=#SUB,
#body=#BODY,
#query= 'SELECT [MID],[HID],[MeC],[LC],[RowCDate]
FROM [JBC].[dbo].[Table1] WHERE RowCDate >= GETDATE()
',
#attach_query_result_as_file=1,
#query_attachment_filename = 'Results.csv',
#query_result_separator = ','

SQL Server : HTML Format in sp_send_dbmail [duplicate]

This question already has an answer here:
HTML Format in sp_send_dbmail
(1 answer)
Closed 7 years ago.
I'm using this query to send daily reports. What changes should I make to the code to get the output in html format?
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'DBMAIL',
#recipients = 'aa#xyz.com',
#query = 'Select Country, CompanyName, round(sum(TotalSale), 0) as Sale, count(*) as DownloadedCount from PW.dbo.SalesReport group by Country, CompanyName order by Country',
#subject = 'Daily Sales Report' ;
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'DBMAIL',
#recipients = 'aa#xyz.com',
#query = 'Select Country,ltrim(rtrim([Store Name])) as Store, round(sum(TotalSale), 0) as Sale, space(3), max(Convert(varchar(10), LastTime, 108)) as [Last update Time] from PW.dbo.SalesReport where len(Country) > 1 group by Country, [Store Name] order by Country, [Store Name]',
#subject = 'Daily Sales Detail'
If you would just quickly consult the official MSDN documentation on sp_send_dbmail - you would easily see this:
[ #body_format= ] 'body_format'
Is the format of the message body. The parameter is of type varchar(20), with a default of NULL. When specified, the headers of the outgoing message are set to indicate that the message body has the specified format. The parameter may contain one of the following values:
TEXT
HTML
Defaults to TEXT.
So just add
#body_format = 'HTML'
to your calls and you should get the HTML format you're looking for.