SQL Agent job calling stored procedure msdb.dbo.sp_send_dbmail @query does not return any records
29-Sep-1111 Leave a comment
ERROR:
SQL Agent job calling stored procedure msdb.dbo.sp_send_dbmail @query does not return any records
SOLUTION
Add the Database Name into the @query
BACKGROUND
This may be because of the default database of the account which executes the SQL Agent job.
EXAMPLE
If @query does not include the database name (three-part naming), it is possible that although the EXISTS may fire, the @query does not.
To solve add the Database Name into the @query.
BEGIN TRY
IF EXISTS(SELECT * FROM Production.vAuditSOCDBTable)
BEGIN
DECLARE @MyBody nvarchar(100)
SET @MyBody = ‘<message>’ + char(13) + char(10)
EXEC msdb.dbo.sp_send_dbmail
@profile_name = ‘<>’,
@recipients = ”,
@blind_copy_recipients = ”,
@query = ‘SELECT * FROM <databasename>..’,
–or possibly @execute_query_database = ‘databasename’,
@subject = ‘subject’,
–@attach_query_result_as_file = 1 ,
@body = @MyBody;
PRINT ‘message’
END
ELSE
PRINT ‘nothing in audit’
END TRY
BEGIN CATCH
SELECT ERROR_NUMBER() ErrorNumber, ERROR_MESSAGE() [Message]
PRINT ‘FAILED’
END CATCH