I have the following TSQL query attempting to run the results and attach to an email but I am having some issues with the formatting of the query, can anyone advise as to why this is not working?
DECLARE @query_attachment_filename VARCHAR(100) = 'Reconciliation-Count-Ending-' + CONVERT(VARCHAR(10), GETDATE(), 112) + '.csv';
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'support',
@recipients = 'johnpaul@energy.co.uk;martin@energy.co.uk',
@subject = 'Reconciliation Count',
@query = N'SET ANSI_WARNINGS OFF;SET NOCOUNT ON;SELECT *
FROM (
select a.New_MessageTypeCode
from New_marketmessagein as a
WHERE CreatedOn between DATEADD(DAY, –1, GETDATE()) and GETDATE()
) AS SRC
PIVOT (COUNT(New_MessageTypeCode ) FOR New_MessageTypeCode IN ([014R], [101], [101P], [101R], [102], [102P], [102R], [105],
[105L], [106D], [106E], [110], [111], [111A], [111L], [111R], [112], [112R], [112W], [114], [115], [115R], [116], [116A],
[116N], [116R],[117D],[117R], [122], [122R], [130D], [130R], [131], [137R], [261], [300], [300S], [300W], [301], [301N],
[303R], [305], [306], [306W], [307], [307W], [308], [310], [310W], [311], [320], [320W], [321], [330], [331], [332], [332W],
[341],[342], [352R], [591], [594], [595], [596], [597], [598], [601], [602], [700], [700W], [701], [701W])) As test ;',
@attach_query_result_as_file = 1,
@query_attachment_filename = @query_attachment_filename,
@query_result_header =0,
@query_result_separator = ' '
the error is:
Executed as user: NT AUTHORITY\NETWORK SERVICE. Error formatting query, probably invalid parameters [SQLSTATE 42000] (Error 22050). The step failed