Generic failure using sp_send_dbmail in SQL Server 2014 - sql-server

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'

Related

Failed to initialize sqlcmd library with error number -2147024809

I created a new email profile with the super admin and I configured the smtp.
Then when I execute this query:
exec msdb.dbo.sp_send_dbmail
#profile_name ='admin_mail',
#recipients = 'firstname.lastname#email.com',
#execute_query_database = 'DashboardPowerBi',
#query = 'select top 20 from Client_1',
#subject= 'Liste des clients',
#body_format ='HTML',
#attach_query_result_as_file = 1;
I get this error:
Failed to initialize sqlcmd library with error number -2147024809
Recently i had an issue related with this, the solution here was to fully qualified the DATABASE + SCHEMA_NAME + TABLE_NAME ('select * from sales..sales_month'), even if you're in the same database.
Regards!
Well, the query is incorrect. You need to specify which columns you are selecting
#query = 'select top 20 * from Client_1',
But rather than using '*', actually list the columns you want.
I also had this error message. It ended up being I didn't have the database tables fully qualified in the query. database.schema.tablename I only had the tablename.
While searching, others had this error because the file attachment was too large.
You can change that in SSMS - Management - Database Mail
In my case, After I had tested the query and encapsulated in a string, I had forgotten to update...
'' AS Blank
to
'''' AS Blank
The Problem is with the directly passing query in #qry.
Try to insert the record to be attached in Global TempTable (##Temp) and try to use that select script with specified column names. Like Below
DECLARE #qry varchar(8000) = 'SET NOCOUNT ON
SELECT
Column1,
Column2
From ##TEMPEMAIL
SET NOCOUNT OFF'
I found that you could not have brackets around your FQDN, so change this
SET #sql = 'SELECT field1, field2, etc FROM [DBNAME].[dbo].[Table1]'
to this instead.
SET #sql = 'SELECT field1, field2, etc FROM DBNAME.dbo.Table1'

Failed to initialize sqlcmd library with error number -2147467259

I am getting error of Failed to initialize sqlcmd library with error number -2147467259
while running below query, I tried with giving database name also but it is not working getting same error again and again. Can someone help me out in this regards.
declare #subject_line varchar (200)
declare #sql_query varchar (8000)
set #subject_line=(select 'Find Highest - ' + convert
(varchar(25),getdate(),120))
set #sql_query=(select 'select a.productname, a.groupid, c.productstatus,
releasedate from #tmpa a
join #tmpb b on a.productname = b.productname and a.prodgroupseqnr = b.maxpg
left join [Repository_PROD].[dbo].[Product_Info] c on a.productname =
c.product_EDP
order by 1')
EXEC msdb.dbo.sp_send_dbmail
#recipients=N'abc#gmail.com',
#subject= #subject_line,
#body= 'Hi ,
Please find attached output of given query .
Regards,
SQLDBA_TEAM
',
#execute_query_database = 'Repository_PROD',
#query_result_header = 1,
#query= #sql_query,
#profile_name ='SQLDBA',
#query_result_width=6000,
#query_result_separator =' ',
#query_no_truncate = 1,
#query_result_no_padding = 1,
#query_attachment_filename ='Find Highest.xls',
#attach_query_result_as_file = 1 ;
You can't use a temporary table when using database mail. You'll also need to include the database name in all tables that are being accessed, for example,
FROM ' + DB_NAME() + '.dbo.TableName makes it portable across databases.
I was also facing the same issue. Then I found the user who is calling the job is not added in SQL server logins folder of Security. I added that user in Security->Logins. It is working fine.

T-SQL inconsistent sp_send_dbmail results

I have a job set up on a handful of servers (all in the same domain). The job sends an email via sp_send_dbmail, and the subject of the email should look like the following format:
=servername (ip address)= Weekly DB Backup to Azure Report
So as a potential example (obviously replace the 0s with actual IP address of the server SQL is running on):
=SQLMACHINE (000.000.000.00)= Weekly Backup to Azure Report
DBmail is configured, and I created the backup job. The T-SQL job step that sends the email has the following script:
SET NOCOUNT ON
DECLARE #ipAddress NVARCHAR(100)
SELECT #ipAddress = local_net_address
FROM sys.dm_exec_connections
WHERE Session_id = ##SPID;
DECLARE #subjectText NVARCHAR(255) = N'=' +
CAST(LEFT(##SERVERNAME, CHARINDEX('\', ##SERVERNAME)-1) AS NVARCHAR) + N'.' +
CAST(DEFAULT_DOMAIN() AS NVARCHAR) + N' ('+ #ipAddress +
N')= Weekly DB Backup to Azure Report'
DECLARE #tableHTML NVARCHAR(MAX) = N'this part works fine'
exec msdb.dbo.sp_send_dbmail #profile_name = 'Production Mail',
#recipients = 'xxx#xxx.com',
#subject = #subjectText,
#body = #tableHTML,
#body_format = 'HTML'
Each of the 5 servers has the same exact job definition - I have 1 source-controlled definition of the job that I use to create the job on each server.
Each week when the jobs run, most of them kick off an email with the expected subject line. Every couple weeks though, an email comes through with the subject SQL Server Message, which is what happens when no subject has been specified. Each time this happens, it could be on any one of the five servers. I'm not sure what's happening, since it should have a subject each time it executes.
EDIT:
This is happening because the #ipAddress variable is null. No idea why
SELECT #ipAddress = local_net_address
FROM sys.dm_exec_connections
WHERE Session_id = ##SPID;
would return null though...
local_net_address will be always NULL if a connection is not using the TCP transport provider. It's likely you use 'Shared memory' in net_transport.
You can force to use TCP when you create a connection, so local_net_address will be populated. E.g. when you open SSMS, you can specify the server name as "tcp:ServerName\InstanceName"
Below also can be used to retrieve the server properties (using TCP transport):
SELECT
CONNECTIONPROPERTY('net_transport') AS net_transport,
CONNECTIONPROPERTY('protocol_type') AS protocol_type,
CONNECTIONPROPERTY('auth_scheme') AS auth_scheme,
CONNECTIONPROPERTY('local_net_address') AS local_net_address,
CONNECTIONPROPERTY('local_tcp_port') AS local_tcp_port,
CONNECTIONPROPERTY('client_net_address') AS client_net_address
Your #ipAddress value could be null
Replace this code:
+ #ipAddress +
with this code
+ ISNULL(#ipAddress,'0.0.0.0') +
to prove that is the issue.

sqlcmd library error in sp_send_dbmail

I am using sp_send_dbmail to send an email containing entries in table Persons. It throws following error -
Failed to initialize sqlcmd library with error number -2147467259.
My query is below -
declare #q varchar(max)
SET #q='SELECT FirstName,LastName FROM dw_extract.dbo.Persons'
USE msdb
EXEC sp_send_dbmail
#profile_name = 'profile_name',
#recipients = 'abc#xyz.com',
#subject = 'T-SQL Query Result',
#body = 'The result from SELECT is appended below',
#execute_query_database = 'dw_extract',
#query = #q
I did some research and found that few people who faced such problem could get rid of it by explicitly stating column names and database of the table used. I did that but still it continues to throw the error.

SQL Job (Send Mail) - error formatting query probably invalid parameters

I know this has come up a lot in the past but none of the fixes I've Googled or found on here has worked for me in this instance.
I'm running a fairly standard SQL Server Agent Job as a Transact-SQL script with the follow details: (replaced some stuff as *** for my boss's sanity)
-- Start T-SQL
USE msdb
EXEC sp_send_dbmail
#profile_name = 'MainProfile',
#recipients = 'test#test.co.uk',
#subject = 'T-SQL Query Result',
#execute_query_database = 'test30',
#query = 'SELECT ReferralReceivedDate,testRef,testcoMetadata.testcoRef,testcoMetadata.TimeSpentWithtester
FROM TestCasesTable, TestcoMetadata
WHERE testcasestable.CaseID = TestcoMetadata.CaseID AND AgencyName = [Test Injury] AND TestcoMetadata.TestcoRef IS NOT NULL AND TestcoRef <> ''
order by ReferralReceivedDate desc',
#attach_query_result_as_file=1,
#query_attachment_filename = 'Results.csv',
#query_result_separator = ','
-- End T-SQL --
The query itself runs fine as a normal query with no issues. The owner of this job has been used on other jobs again with no problems. In the step properties the Database selected is the same one as that mentioned in the #execute line.
I have a feeling this is either falling over the way it's trying to create the csv or something to do with permissions with dbmail part. I'm only a part time DBA so this has now lost me and I need help.
Replace this:
TestcoRef <> ''
With this:
TestcoRef <> ''''
You are creating dynamic sql, so you need to escape the single quotes.
So I never did get this working, but it turns out my boss already had something cooked up.
He had a stored procedure set up to run a batch file that was using an emailer exe to send the mail out, as its apparently better/more powerful than SQL mail.
I simply copied his S.P and amended it to include my query.

Resources