I have a procedure that pulls data from my database and uses MSDB.DBO.sp_send_dbmail to send out e-mails. The procedure itself runs without a hitch when I use ‘EXEC myprocedure’. But when I set up a job for the procedure, the job fails with the following error
‘Error formating query, probably invalid parameters [SQLState
42000](Error 22050). The step failed’
There is one step in the job with the TSQL statement ‘EXEC myprocedure’, using the database that my procedure is stored on. Does anyone know what could be causing this error?
Update
I’ve narrowed the problem down. It’s something with the Exchange server I use. I was using a domain address (ie. mail.mycompany.com) as the ‘Server name’ under Database Mail’s account configuration wizard. I was unable to send e-mails to listservs and external users using this domain address. I talked to our Exchange guy and he recommended using the actual IP address of one of the mail servers (ie. 10.123.53.53). That fixed the problem with listservs and external users, but now I am unable to send e-mails when I run my procedure using a job (the procedure itself executes properly when I manually run it). Does anyone know what criteria on our Exchange server I will need to change to fix this?
The problem was with the @query parameter used by sp_send_dbmail. For some reason, my SQL Server Agent account (which was a domain administrator) was denied access to use sp_send_dbmail with the @query parameter. I ended up dropping the @query parameter altogether and putting everything in the @body parameter. The @body parameter became a concatenation of regular text and what returned from a SELECT query.