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

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

Related

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,

sp_sent_email - attachment as grid

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.

SQL Server: DB Mail Not getting triggered after certain Size

I am sending csv file from SQL Server using below query.
EXEC #RtnCode = sp_send_dbmail
#profile_name = 'Mail',
#query_result_separator=#Separateur,
#recipients = 'xxx#xxx.com;',
#subject = #mailSubject,
#query = #STMT,
#Attach_Query_result_as_file = 1,
#query_attachment_filename = 'filename.csv',
#query_result_header = 1,
#query_result_width = 32767,
#query_result_no_padding = 1
Mail size in 'Database Mail' was configured as 1 MB. I have changed it to 5 MB. And restarted SQL Server agent. But Mails are not getting triggered, even though it is getting queued in Mail Queue.
Please help,
Thanks in advance.

Sending query results via email via email attachment every first day of every month on SQL Server 2012

My requirement:
Send the query result via email attachment on first day of every month.
The work I've been doing manually:
I have to run this query every first day of each month by changing the date range.
Then I export the result acquired in .csv format and send this csv file as an attachment
I needed suggestions from you people on how shall I automate this process:
Shall I set up a Job on SQL Server 2012, but yes, the I'll have to modify the date range.
Please suggest on how to move forward.
Any help, much appreciated.
As you mentioned, Create a Job and schedule it to run on first day of every month. Considering you have enough knowledge on creating a job.
Go to Job properties -> schedules -> and make the following setting
Occurs every first day of every 1 month(s) at 12:00:00. Schedule will
be used starting on 07-12-2016.
Change the timing(at which time it should run on first day of month) based on your business requirement. It can be set under Daily frequency-> Occurs once at:
This process can also be automated by another way by using a Windows batch file.You can schedule it using Windows scheduler.
Below will be contents of batch file
Echo off
sqlcmd -u <username> -p <password> -S <server name> -d <database name> -i <sql file location> -o <output result file location>
Powershell.exe -executionpolicy remotesigned -File <location of powershell file>
The powershell file trigger an email when bat file is run.
Contents of powershell file
$smtpserver = "<smtp server name>"
$from="mail id"
$to="<mail id"
$a = Get-Date
$subject= "<subject line> `r"+ $a.Month +"/"+$a.Day +"/"+ $a.Year
$body=""
$attachment="File location"
Thanks,`n "
$mailer = new-object Net.Mail.SMTPclient($smtpserver)
$msg = new-object Net.Mail.MailMessage($from,$to,$subject,$body,$data1,$a)
$msg.IsBodyHTML = $true
$mailer.send($msg)
I use SQL Agent for send results via email like this:
/*
First you should set up SQL Mail Profile.
Please change #dbName, #SQLscript, #mailbody and mail account values. When changing your #SQLscript value be careful that replace (with CTRL+H) single quota (') to double quotas ('').
*/
DECLARE #dbName nvarchar(50), #SQLscript nvarchar(4000), #subject varchar(100), #mailfrom varchar(100), #mailbody nvarchar(4000), #jobName varchar(100)
SELECT #jobName = name from msdb..sysjobs where job_id = $(ESCAPE_NONE(JOBID))
SELECT #mailfrom = ##SERVICENAME + ' <' + cast(SERVERPROPERTY('ComputerNamePhysicalNETBIOS') as varchar(50)) + '#domain.com>'
SELECT #subject = N'SQL Server Job Result [Job: ' + #jobName + ']'
SELECT #dbName = 'Database'
SELECT #SQLscript = '
INSERT INTO [Database].[Schema].[Table] (
Column1
,Column2
) VALUES (
''Value1''
,''Value2'' )
'
SELECT #mailbody = N'
Depending on case number 1234-5678-90 your script executed on <b>' + ##SERVERNAME + N'</b> instance and <b>' + #dbName + '</b> database. Script info and results are shown below. <br><br>' +
'<b>Script: </b><br>' + #SQLscript + '<br><br>' +
'<b>Result: </b><br>'
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'sqlmailprofile',
#recipients = '<mail1#domain.com>;<mail2#domain.com>',
#copy_recipients = '<mail3#domain.com>',
#from_address = #mailfrom,
#reply_to = '<mail3#domain.com>',
#subject = #subject,
#body = #mailbody,
#body_format = 'HTML',
#importance = 'HIGH',
#execute_query_database = #dbName,
#query = #SQLscript
/* If you want to send results with attached file:
#attach_query_result_as_file = 1,
#query_attachment_filename = 'script_output.csv',
#query_result_separator=#tab,
#query_result_width =32767,
#query_result_no_padding=1,
#exclude_query_output=1,
#query_result_header=1
*/

set delimiter when using sp_send_dbmail (csv file)

I have a query that brings me back a result set but when I use sp_send_dbmailto send an email to someone containing this result set as a CSV file it opens in excel in the incorrect format! I know that I can correct this format through excel but I don't want the user to do that! I want them to just be able to open the file and everything be visible in the correct format. Below shows how I am creating the CSV file and emailing it out the someone (I am also specifying the seperator but it doesn't work and I can't figure out why):
EXEC msdb.dbo.sp_send_dbmail
#profile_name='TestProfile',
#recipients='Test#gmail.com',
#subject='Test message',
#body='This is a test.',
#query = 'Select firstName, LastName, Address, Score from TestData.dbo.Student',
#query_result_header = 0,
#exclude_query_output = 1,
#append_query_error = 1,
#attach_query_result_as_file = 1,
#query_result_separator = ',',
#query_result_width = 25,
#query_attachment_filename = 'Test.csv',
#query_result_no_padding = 1
Once the CSV File is received and opened all the data is represented in the first column, which isn't the desired results!
Screenshot of my list seperator settings
I struggled with this issue for a couple of days , but finally got it to work
#query_result_separator =' ', did the trick, it's TAB as the result separator.
Full code
EXEC msdb.dbo.sp_send_dbmail
#profile_name ='MailProfile',
#from_address = 'def#abc.com',
#recipients = 'Abc#abc.com',
#body = #varBody,
#body_format = 'HTML',
#execute_query_database ='MyDB',
#query = #VarSQL,
#attach_query_result_as_file = 1,
#query_result_separator =' ',
#exclude_query_output =1,
#query_result_no_padding=1,
#query_result_header =1,
#query_attachment_filename ='MyDB.csv'
If you are using Excel anyway, you can override Excel list separator and remove the problem all together, across every single regional setting out there.
Add the following line in the beginning of the CSV file: sep=;
In your example you would have this inside your #query.
..
#query_result_separator = ';',
#query = '
print ''sep=;''
SELECT 1,2'
..
Content of csv:
sep=;
1;2
Result; correct separation. Always!
You can't count on user regional settings or the application used to open the file.
Besides, any Excel user should know about Data->Text To Columns function.
The only thing you should take care of are fields that might contain the field separator (,) like addresses which should be wrapped with text qualifiers (e.g. ").
I think I could reproduce your issue with the data you provided. I found the answer in this superuser post.
It seems, Excel ignores your list separator if it is the same character as another already used character (for example decimal separator), it will work when you switch decimal separator to something else. But since you need this working on other client machines, too, you should consider switching to another csv-separator altogether (;?)