Search code examples
sqlsql-serversql-server-agent

SQL Server Agent Emails: Error Formatting Query


I was running into an issue when creating and implementing a new SQL server agent job to run and email the results of a simple query:

EXEC ms.dbo.sp_send_dbmail
@profile_name = 'Main DB Mail Profile',
@recipients = '[email protected]',
@subject = 'Basket Report',
@query = N'Select Store, Date, Sum(Amount) as DailyTotal, COUNT(CAST(Trans as varchar(30))+CAST(Register as Varchar(30))) as DistinctTransactions
From BasketAnalysis
Where Date = dateadd(day,datediff(day,1,GETDATE()),0)
GROUP BY Store, Date
ORDER BY Store ASC;',
@attach_query_result_as_file = 1,
@query_attachment_filename = 'BasketReport.txt'

I kept running into a mysterious error message in the history log for the task.

Executed as user: NT AUTHORITY\NETWORK SERVICE. Error formatting query, probably invalid parameters [SQLSTATE 42000] (Error 22050). The step failed.

Has anyone had any luck getting more information on these errors and how to resolve them?


Solution

  • Digging around, I found a large number of different potential solutions, that I thought I would try to compile some of them here.

    1. User Permissions: The SQL Server Agent user needs to have sufficient privileges to be able to execute and email. The user needs to have the DatabaseMailUserRole (under msdb user mapping) server role. The SQL Configuration Manager gives you the ability to view and adjust the Server Agent user if necessary, experimenting with a Server Agent exclusive user can be helpful!
    2. Run the query in a new query window: Dumb as this is, I totally neglected to run the query outside of the job itself at first. I realized this, and this gave me some more error information than what was being logged in the Server Agent history.
    3. Check your email parameters: This is my problem, but I was following this tutorial but was getting this error because I neglected to include the '@execute_query_database' parameter in my query. Adding that, pointing to my relevant database, was the missing piece.