Link to home
Start Free TrialLog in
Avatar of Mark B
Mark BFlag for United States of America

asked on

ms sql database mail and csv file attachments - how to "escape" correctly

How do I ensure that query results placed in a csv file will "escape" correctly? Below works ok, but if there is a comma in the data, the csv file does not show correctly in excel. Is there some way to contain each cell's data in the csv so it will open correctly in excel?

Thanks.


DECLARE @sub VARCHAR(100)
DECLARE @qry VARCHAR(1000)
DECLARE @msg VARCHAR(250)
DECLARE @query NVARCHAR(1000)
DECLARE @query_attachment_filename NVARCHAR(520)

SELECT @sub = 'Nightly Report'
SELECT @msg = 'This is an automated message.'
SELECT @query = 'SELECT * FROM [sem].[dbo].[04AGSEMQuoteFormProduction] WHERE [sem].[dbo].[04AGSEMQuoteFormProduction].[ServerTime] >= cast(getdate() as date)'

SELECT @query_attachment_filename = 'report.csv'

EXEC msdb.dbo.sp_send_dbmail
            @profile_name = 'AG Reporting',
            @recipients = 'email@email.com',
            @body = @msg,
            @subject = @sub,
            @query = @query,
            @query_attachment_filename = @query_attachment_filename,
            @attach_query_result_as_file = 1,
            @query_result_header = 1,
            @query_result_width = 256 ,
            @query_result_separator = '	' ,
            @query_result_no_padding =1;

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of chaau
chaau
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Mark B

ASKER

Thanks, #2 worked.