sp_send_dbmail Error In Microsoft SQL Agent Job - sql-server

I’m trying to send an email from a scheduled SQL Agent job using sp_send_dbmail and receive the following error:
Msg 22050, Level 16, State 1, Line 0
Error formatting query, probably invalid parameters
Msg 14661, Level 16, State 1, Procedure sp_send_dbmail, Line 504
Query execution failed: Msg 15404, Level 16, State 19, Server MyServer, Line 1
Could not obtain information about Windows NT group/user 'MyDomain\sqlagent', error code 0x5.
Here is the code from the job step:
DECLARE #SQL NVARCHAR(400)
SELECT #SQL = 'SELECT COUNT(staff_id) FROM Staff'
EXEC msdb.dbo.sp_send_dbmail
#recipients = 'me#myemail.com',
#subject = 'Email Alert',
#body = 'Test',
#query = #SQL,
#execute_query_database = 'MyDB'
SQL Agent is running under a domain account [MyDomain\sqlagent]. I granted this user db_owner permission in the MyDB database in addition to adding it as a member of the DatabaseMailUserRole in msdb. Still no luck. If I remove the #query and #execute_query_database parameters it will send a ‘test’ email. However, I need to attach the results from the query.
Any help is appreciated, thanks.

I've run into some strange errors with AD in the past. I would recommend checking that the account you are running this under has it's attributes readable within AD. The quickest way to do that would be to run
exec xp_logininfo 'MyDomain\sqlagent'
and seeing if you get the same error. If you do, check the security properties of the domain account [right click the user in Active Directory > Properties > Security tab] and set Read permissions for Authenticated Users.

This worked for me.
'SELECT columnname from YourDatabase.SchemaName.tablename'
I found this answer here.
https://social.msdn.microsoft.com/Forums/sqlserver/en-US/7869b033-80f1-4594-a77e-fb6dce582fb4/error-msg-when-sending-email-using-spsenddbmail?forum=transactsql

Related

SQL Server returns error with sp_trace_generateevent

I get an error from one of my databases when trying to execute this one
create or alter procedure [dbo].[test_sp]
with execute as owner
as
SELECT SUSER_SNAME()+ ' '+ USER_NAME();
begin
exec master..sp_trace_generateevent #eventid = 82 ,
#userinfo=N'test'
end
GO
exec [dbo].[test_sp]
Error:
Msg 8189, Level 14, State 10, Procedure master..sp_trace_generateevent, Line 1 [Batch Start Line 9]
You do not have permission to run 'SP_TRACE_GENERATEEVENT'.
Granted ALTER TRACE to my user (which returns in SUSER_SNAME()), but it wasn't help
The same script on the second database (same server) works without errors.
What else can it be?
You're trying to run this with EXECUTE AS OWNER, and the owner is a database-level principal and you can't operate outside the current database while impersonating a database-level principal. Switch to EXECUTE AS CALLER (the default) to have the caller's identity used to run the proc in master. eg
create or alter procedure [dbo].[test_sp]
with execute as caller
as
SELECT SUSER_SNAME()+ ' '+ USER_NAME();
begin
exec master..sp_trace_generateevent #eventid = 82, #userinfo = N'test'
end
GO
exec [dbo].[test_sp]
This can be made to work with owner-impersonation by marking the database as TRUSTWORTHY. See: Extending Database Impersonation by Using EXECUTE AS and Guidelines for using the TRUSTWORTHY database setting in SQL Server

Error with automated mail

I'm working on a piece of code that will email me the results of some queries twice a day from SQL Server 2016. When I run this bit of code from my developer window, it works fine. When I run it from the job, I get this error:
Executed as user: myDB\svcAGCRM2016_PRD. Failed to initialize sqlcmd
library with error number -2147467259. [SQLSTATE 42000] (Error 22050).
The step failed.
This is the code that runs:
declare #recipient_name varchar(500)
declare #SqlQuery varchar(max)
SET #SqlQuery='exec [myDB].[dbo].[sp_DailyRejectionRate]'
set #recipient_name = 'myemail#email.com'
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'SMTPProfile',
#recipients =#recipient_name,
#subject = '[INFO]'
,#query='exec [myDB].[dbo].[sp_DailyRejectionRate];
I'm running this from a service account. Weirdly, not with the name of the service account in the error. Actually, I can't even find that account.
In the code, I'm doing an exec because otherwise the query is too long for query.
The service account that runs this is an SA. Also, I wrote another query this morning that sends out email with not problems today.
Any ideas?
What if you explicitly specify the user in the query string?
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'SMTPProfile',
#recipients =#recipient_name,
#subject = '[INFO]'
,#query='execute as user='my_sa_user' exec [myDB].[dbo].[sp_DailyRejectionRate];

Azure stored procedure not executing when call sp_execute_remote

I try to do a across database query in AZURE SQL elastic pools but it's not working.
My stored procedure is:
CREATE PROCEDURE [dbo].[CreateNewSurveyQuestion]
#QuestionString varchar(MAX)
AS
INSERT INTO CTRL_Survey(SurveyQuestion)
VALUES (#QuestionString)
--create new survey in new qm
EXEC sp_execute_remote
N'QCentralDS',
N'INSERT INTO [dbo].[SurveyTbl]([Question], [IsActive], [CreateDate])
VALUES(#QuestionStringValue, 1, GETDATE())'
, N'#QuestionStringValue varchar(300)'
, #QuestionStringValue = #QuestionString
EXEC stored procedure [not working with error message below]
EXEC [dbo].[CreateNewSurveyQuestion]
#QuestionString = N'Add a new question'
Error message:
Msg 64, Level 20, State 0, Line 1
A transport-level error has occurred when receiving results from the server. (provider: TCP Provider, error: 0 - The specified network name is no longer available.)
I am sure all EXTERNAL DATA SOURCE are correct. And I can run this part in my SQL Server Management Studio successfully.
EXEC sp_execute_remote
N'QCentralDS',
N'INSERT INTO [dbo].[SurveyTbl]([Question], [IsActive], [CreateDate])
VALUES(#QuestionStringValue, 1, GETDATE())'
, N'#QuestionStringValue varchar(300)'
, #QuestionStringValue = #QuestionString
Is there any issue with this mode of work, or exists another way to do it?

Generic failure using sp_send_dbmail in SQL Server 2014

I'm trying to use sp_send_dbmail to send the results of a query through a SQLAgent job in SQL Server 2014. I believe I have my DBMail profile set up properly but when running this:
exec msdb.dbo.sp_send_dbmail
#profile = 'TestProfile',
#recipients = 'testmail#gmail.com',
#subject = 'Test',
#query = 'SELECT id FROM TestTable',
#attach_query_result_as_file = 1,
#query_attachment_filename = 'TestValues.txt'
I get the following error message:
Failed to initialize sqlcmd library with error number -2147467259.
Googling this error message didn't turn up anything useful, likely due to the generic error number. Anyone have some insight into this error message?
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'

set database to multi_user through management studio

I have had to set my database to single_user mode to allow for a dbcc checkdb repair and now I am unable to get my database back to multi_user. I have tried the following command in a query window against the master database but it hasn't worked as suggested by another Stack overflow post:
USE [master];
GO
ALTER DATABASE mydb SET MULTI_USER WITH ROLLBACK IMMEDIATE;
GO
I get the following error:
Msg 5064, Level 16, State 1, Line 2 Changes to the state or options of
database 'mydb' cannot be made at this time. The database is in
single-user mode, and a user is currently connected to it.
Msg 5069,
Level 16, State 1, Line 2 ALTER DATABASE statement failed.
If I right click on the database and try selecting properties then it errors saying that it is already in use.
Any help would be greatly appreciated.
Try killing the existing connection and setting MULTI_USER in the same batch:
USE master;
GO
DECLARE #sql nvarchar(MAX);
SELECT #sql = STRING_AGG(N'KILL ' + CAST(session_id as nvarchar(5)), ';')
FROM sys.dm_exec_sessions
WHERE database_id = DB_ID(N'mydb');
SET #sql = #sql + N';ALTER DATABASE mydb SET MULTI_USER;';
--PRINT #sql;
EXEC sp_executesql #sql;
GO
To get the session that was tied to the database I ran:
SELECT request_session_id
FROM sys.dm_tran_locks
WHERE resource_database_id = DB_ID('mydb')
This yielded a processid of 55
I then ran:
kill 55
go
And I was the able to use the alter multi_user line that was previously not working
The most likely reason why you're getting this error is that you still have the original session open that you used to set the database to single user. If you execute the above SQL in the same session that you set the database to single user in, it will work.
First try selecting the master database and run the alter command.
If it does not work, There exists some open connections to database and you can check and kill the processes
use master
GO
select
d.name,
d.dbid,
spid,
login_time,
nt_domain,
nt_username,
loginame
from sysprocesses p
inner join sysdatabases d
on p.dbid = d.dbid
where d.name = 'dbname'
GO
kill 52 -- kill the number in spid field
GO
exec sp_dboption 'dbname', 'single user', 'FALSE'
GO

Resources