I am working on code that will send a results of my query via email. Mostly it works fine but I have a question: Is there any way that I could include a current date in the file name? Instead of having:
@query_attachment_filename = 'report.csv'
I would like to have something like:
report_getdate()\_.csv
I'm using SQL Server Management Studio 2016 Related topic: How to send a query result in CSV format?
My query looks like this and it works well. Just need to change the name of the file
Any help appreciated. Thank you
DECLARE @AccountSite VARCHAR(255)
DECLARE @Query VARCHAR(MAX)
SET @AccountSite = '[sep= ' + CHAR(13) + CHAR(10) + 'AccountSite]'
SET @Query = 'SELECT
[AccountSite] ' + @AccountSite + '
,[Account Name]
,[Title]
,[Status]
,[Opened Date]
,[Closed Date]
,[Geo]
,[Country]
,[Region]
,[Marketing Name]
,[Case Number]
FROM [Reporting].[dbo].[Rep]'
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'BI Server'
,@recipients = '[email protected]'
,@query = @Query
,@subject = 'Report'
,@body = 'Attached is the latest extract of the report'
,@query_attachment_filename = 'report.csv'
,@query_result_separator = ' '
,@attach_query_result_as_file = 1
,@query_result_no_padding= 1
,@exclude_query_output =1
,@append_query_error = 0
,@query_result_header = 1
,@query_result_width = 32767;
@query_attachment_filename. You are explicitly providing the value'report.csv'so that's the name the file gets. Just supply different value, like you are with@query..csvextension butsp_send_dbmailcannot generate a CSV file in any accepted sense of the definition, particularly with respect to RFC4180 Common Format and MIME Type for Comma-Separated Values (CSV) Files. Try sending data containing,,"or linebreak characters and see how badly it fails. Consider external tools capable generating proper CSV files like SSRS (at least since SQL Server 2014 anyways) and PowerShell.