Generic failure using sp_send_dbmail in SQL Server 2014

为君一笑 提交于 2019-12-01 07:03:18

I found that despite both my query window (for testing) and SqlAgent job were pointing at my desired DB, sp_send_dbmail doesn't seem to have any database context. My original post was failing because SQL didn't know where to run SELECT * FROM TestTable. The fix is to provide sp_send_dbmail with database context by either fully qualifying your table in the @query parameter:

@query = 'SELECT id FROM testDB.dbo.TestTable'

or by providing the optional @execute_query_database parameter:

@execute_query_database = 'testDB'

Enable sysadmin server role for the account that is used to run the SQL Server Agent.Below are the screenshots.

Error

Fix

Now the SQL Server Job runs without any errors and I get an email from dbmail.

There's another reason why you might get this error; if the query has an issue.

In our case we had (note that it's not due to a syntax error; note the missing quotes):

DECLARE @EmailQuery varchar(max) = 'select 
                                    e.Field1,
                                    REPLACE(REPLACE(e.ExceptionReason, CHAR(13), ''), CHAR(10), '') ExceptionReason,
                                    e.UserName
                                from dbo.tblException e'

Once we corrected it as follows, it worked fine:

DECLARE @EmailQuery varchar(max) = 'select 
                                    e.Field1,
                                    REPLACE(REPLACE(e.ExceptionReason, CHAR(13), ''''), CHAR(10), '''') ExceptionReason,
                                    e.UserName
                                from dbo.tblException e'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!