Sending File through database Mail - sql

I am trying to sending a file through Database mail , when i execute the query below without #query option mail is triggered but when i include the #query option i get the error mentioned.
if ##rowcount >0
EXEC msdb.dbo.sp_send_dbmail #profile_name = ' Errormail',#recipients='arunkumarb#mobiusservices.in;',
#subject = 'A new Record created in the SSORunError Log Table' ,
#body = 'A new Record created in the SSORunError Log Table' ,
#query = 'select * from ip',
#attach_query_result_as_file = 1,
#query_result_width = 4000,
#query_attachment_filename = 'Details.txt'
Error Message :
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 208, Level 16, State 1, Server , Line 1
Invalid object name 'ip'.
Thanks in advance

Try using fully qualified name for the table:
SELECT * FROM yourDatabase.yourSchemaName.ip
You can also set #execute_query_database parameter of your call to sp_send_dbmail to contain the name of your database (although I think that using fully qualified name should be enough).

Related

SQL profile name error when executing job

I'm trying to make a scheduled job, so that on the day 25 of every month it sends an e-mail with some information. The code I have right now is:
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'Main DB Mail profile',
#recipients = 'myemail#mydomain.net',
#subject = 'PG25',
#query = N'SELECT CONVERT(date, docdata), adoc, nome, etotal, aprovado FROM fo
WHERE aprovado LIKE "0"
AND pdata BETWEEN DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0) AND DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), 25)',
#attach_query_result_as_file = 1,
#query_attachment_filename = 'results.txt'
but when I execute this code I get this error:
Msg 14607, Level 16, State 1, Procedure msdb.dbo.sysmail_verify_profile_sp, Line 42 [Batch Start Line 5]
Profile name is not valid
Any thoughts on how I can get this to work?
You need to make sure that profile name you are calling has to exist in Database Mail. In order to check, do the following:
Expand Management within your instance;
Then, right click and Configure Database Mail;
After this, if you already have a profile defined, you can choose the 4th option to check the profile name. Otherwise, you need to define a new one (careful on the profile name you choose because it has to match to the one you're calling);

Send an email with CSV attachemt in SQL Server(SQL Job is failing)

When we run below script manually we are getting an email with attachment but when we are running through SQL Job getting below error.
Executed as user:venu: Failed to initialize the sqlcmd library with
error number -2147467259. [SQLSTATE 42000] (Error 22050). The step
failed.
/* To send an Email Attachment to the User */
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'DBMail',
#recipients = 'venu.siripuram#gamil.com',
#query = 'SET NOCOUNT ON
Select Recordtype as TransType, SKU, SKU1 Style, SKU2 Color,
SKU3 Size, UPC
from CIMSDE.dbo.ExportTransactions with (nolock)',
#subject = 'SKU Transactions',
#attach_query_result_as_file = 1,
#query_attachment_filename = 'sample.csv',
#query_result_separator = '',
#query_result_no_padding = 1
Most probably the error was due to 'File size limit was exceeded'.
You can set the file size (in bytes) using the following command:
EXECUTE msdb.dbo.sysmail_configure_sp 'MaxFileSize', '10000000';
you can get all set values by executing the following:
exec msdb.dbo.sysmail_help_configure_sp

Replace function requires 3 arguments

I am trying to fetch data from SQL to excel and it is giving me the below error
My Query in SQL Server
DECLARE #Delimiter Char(1)
SET #Delimiter = CHAR(9)
EXEC MSDB.dbo.sp_Send_DBMail
#profile_name = 'K2MailSetup',
#Recipients='abs#test.com',
#Subject='Extraction Report',
#Body='Hi,
Please find attached extraction report as required. ',
#Query='set nocount on;Select Coalesce(replace(replace(A.[type], char(10), ''), char(13), ''),'') as Type FROM [EU_OTH_REG].[dbo].[TBL_EU_OTH_TXN_REG_RSDS] A',
#Attach_Query_Result_As_File = 1,
#Query_Result_Header = 1,
#Query_Attachment_Filename = 'Report.csv',
#Query_Result_Separator = #Delimiter,
#query_result_width =32767,
#query_result_no_padding=1
========================================================================
It is giving me below 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 517
Query execution failed: Msg 105, Level 15, State 1, Server MYKULK2DB01Q\MSSQLSTG, Line 1
Unclosed quotation mark after the character string ') as Type
FROM [EU_OTH_REG].[dbo].[TBL_EU_OTH_TXN_REG_RSDS] A
'.
Msg 102, Level 15, State 1, Server MYKULK2DB01Q\MSSQLSTG, Line 1
Incorrect syntax near ') as Type
FROM [EU_OTH_REG].[dbo].[TBL_EU_OTH_TXN_REG_RSDS] A
========================================================================
The strange thing is that when I just run the query it provides me result but when I try to create report out of it by using the above excel steps and parameters it gives me error.
You need to check the quote in the #Query variable.
I replaced it in the following;
#Query='set nocount on;Select Coalesce(replace(replace(A.[type], char(10), ''''), char(13), ''''),'''') as Type FROM [EU_OTH_REG].[dbo].[TBL_EU_OTH_TXN_REG_RSDS] A'
From the docs: SQL Server Replace
The syntax for REPLACE() goes as follows:
REPLACE ( string_expression , string_pattern , string_replacement )
As you can see, all parameters should be in string format. Make sure all parameters are encased in '' for your script to work.

Passing Cursor Result to send_dbmail as a Parameter

I've never worked with cursors before, and upon reading, this may not be the best approach, so by all means, makes suggestions.
I am attempting to pass the result set of a cursor to a query. Here's what I have so far:
DECLARE #PM varchar(50),
#c1 as CURSOR
SET #c1 = CURSOR FOR
SELECT PM
FROM PMtable
OPEN #c1;
FETCH NEXT FROM #c1 INTO #PM;
WHILE ##FETCH_STATUS = 0
BEGIN
DECLARE #emailBody nvarchar(max)
SET #emailBody = 'SELECT * FROM othertable WHERE PM = ' + #PM + ' ORDER BY PM';
EXEC msdb.dbo.sp_send_dbmail
#recipients = 'me#me.com',
#subject = 'test',
#query = #emailBody;
FETCH NEXT FROM #c1 INTO #PM;
END
CLOSE #c1;
DEALLOCATE #c1;
The idea is to send the #emailBody query result set as an email for every result in the cursor. For example, say the cursor returns three results: Bob, Jim, and Joe. I want to loop run the #emailBody query for each result from the cursor and send an email for each result.
When I run the query as is, I receive an error saying:
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 [Batch Start Line 0]
Query execution failed:
Msg 207, Level 16, State 1, Server SERVER, Line 9 Invalid column name
'Bob'.
Msg 207, Level 16, State 1, Server SERVER, Line 1 Invalid
column name 'Bob'.
I have no clue what's going on. Any ideas?
You need to add '':
SET #emailBody='SELECT * FROM othertable WHERE PM = ''' + #PM + ''' ORDER BY PM';
Be aware of possible SQL Injection.
How it works:
Msg 207, Level 16, State 1, Server SERVER, Line 9 Invalid column name 'Bob'.
SELECT * FROM othertable WHERE PM = Bob ORDER BY PM
vs.
SELECT * FROM othertable WHERE PM = 'Bob' ORDER BY PM
Please keep in mind that ORDER BY PM for one value does not change anything.

SQL Sending attach query in email as .csv

I am trying to send an query as an attached .CSV in a email. Here is what I have.
EXEC msdb.dbo.sp_send_dbmail #recipients='bdorner#fascinations.net',
#profile_name= 'MyMailProfile',
#subject='new Items',
#body='New Items',
#query= 'select itemlookupcode, * from Item where
(datecreated BETWEEN DATEADD(DAY, - 100, CURRENT_TIMESTAMP) AND DATEADD(day, - 0, CURRENT_TIMESTAMP))
',
#attach_query_result_as_file=1
#query_attachment_filename = 'test.csv'
I keep getting a error Msg 102, Level 15, State 1, Line 11
Incorrect syntax near '#query_attachment_filename'.
I do have an email that send out a query in a body of an email. If that code will help let me know.
Thank you for the Help,
Brian
You are missing a comma :
#attach_query_result_as_file=1**,**
#query_attachment_filename = 'test.csv'
When you get a syntax error, always look for syntax problems in your query!
You're missing a comma after the #attach_query_result_as_file. That's why you get a syntax error pointing at the next line after.