Friday, February 24, 2012

Database mail in SQL Server 2005 - Email Query Results in Excel format?

Using database mail in SQL Server 2005, I can email the query results in form of a .txt attachment.

EXEC msdb.dbo.sp_send_dbmail
@.recipients=N'userName@.domain.com'
,@.body='Message Body'
,@.subject ='Message Subject'
,@.profile_name ='Mailer Profile'
,@.query ='SELECT * FROM SalesDb.dbo.SalesHistory'
,@.attach_query_result_as_file = 1
,@.query_attachment_filename ='Results.txt'

I want the query results in a CSV or preferably in Excel format. Can I achive that using database mail?

You have several options.

(a) You could use bcp to create the file, and the email the file as an attachment.

(b) You could revise the existing query to create csv formated data like this:

SELECT ''' + ',' + column1 + ',' + Col2 + ',' + {etc} + ''' FROM SalesDb.dbo.SalesHistory

(c) You could use xml to create a xml file that would be easily handled by Excel.

For the xml option, check in Books Online, Topics: OpenXML, FOR XML, Writing XML.

No comments:

Post a Comment