Sql-server – Error using sp_send_dbmail with a @query parameter

database-mailsql serversql-server-2016

This has been asked many times, and every time I've seen, the solution is to add the @execute_query_database parameter. Well, as you can see, I have that parameter and this code:

EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'GMail',
@recipients = 'brady@bradykelly.net',
@subject = 'Snappy Referrals', -- add date
@body = 'Hello, DB mail!',
@execute_query_database = 'SeniorExecs',
@query = N'SELECT * from Language'

Still gives the error below as long as the @query parameter is present. When I comment out that one line, the proc call works and the mail is sent.

Failed to initialize sqlcmd library with error number -2147467259.

When I examine the DB Mail logs, in the Sql Server section, everytime I try and execute the proc, an entry like this gets added:

Unknown,Disallowing page allocations for database 'WideWorldImporters'
due to insufficient memory in the resource pool 'default'.

At this point, the only thing to say about database WideWorldImporters is that it is on the same SQL server. I encountered it nowhere setting up a mail profile and user account.

Best Answer

Going an entirely different direction than what I was thinking of in the comments, if you're running this from within a job, this blog post suggests adding the SQL Agent account to the sysadmin fixed server role.

I doubt you have to go that far to fix this, and I suspect you only really need to grant the SQL Agent user (or whatever user owns the job in question) a minimum set of permissions, which are execute permissions on the sp_send_dbmail procedure, ensuring it's a member of the DatabaseMailUser database role in the msdb database, and finally, making sure it can access the data being returned by the query you're passing to the sp_send_dbmail routine itself.