I've seen this discussed in another thread however a solution was never found. This came up after we applied the SQL Server 2008 R2 SP2 patch to our DBMS which had previously been at 2008 R2 SP1. The symptoms are that I can run a query which uses a linked server as both myself (dba/sa) and the affected application service account inside MSSMS (both are AD accounts). But when I put the same query in sp_send_dbmail as follows:
EXECUTE MSDB..sp_send_dbmail
@profile_name = '<some profile>',
@recipients = '<some user>',
@copy_recipients = '',
@blind_copy_recipients = '',
@subject = '...',
@body = '...',
@query = '<query using linked server>',
@execute_query_database = '<some db>',
@attach_query_result_as_file = 1,
@query_result_width = 32767,
@append_query_error = 1
the following error is produced:
Msg 22050, Level 16, State 1, Line 0
Error formatting query, probably invalid parameters
Mail queued.
The email that is sent out has the following in the attachment:
Msg 7437, Level 16, State 1, Server <MyServer\MyInstance>, Line 1
Linked servers cannot be used under impersonation without a mapping for the impersonated login.
This is confusing because the linked server has no mappings defined so impersonation should not be in play. It is set up to use "current login's security". So I wondered if maybe the sp_send_dbmail was substituting in another account. I changed the @query variable to 'select system_user'. There was no error during execution and it returned <MyDomain>\<Me> in the attachment.