SQL profile name error when executing job - sql

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);

Related

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.

Sending query results via email via email attachment every first day of every month on SQL Server 2012

My requirement:
Send the query result via email attachment on first day of every month.
The work I've been doing manually:
I have to run this query every first day of each month by changing the date range.
Then I export the result acquired in .csv format and send this csv file as an attachment
I needed suggestions from you people on how shall I automate this process:
Shall I set up a Job on SQL Server 2012, but yes, the I'll have to modify the date range.
Please suggest on how to move forward.
Any help, much appreciated.
As you mentioned, Create a Job and schedule it to run on first day of every month. Considering you have enough knowledge on creating a job.
Go to Job properties -> schedules -> and make the following setting
Occurs every first day of every 1 month(s) at 12:00:00. Schedule will
be used starting on 07-12-2016.
Change the timing(at which time it should run on first day of month) based on your business requirement. It can be set under Daily frequency-> Occurs once at:
This process can also be automated by another way by using a Windows batch file.You can schedule it using Windows scheduler.
Below will be contents of batch file
Echo off
sqlcmd -u <username> -p <password> -S <server name> -d <database name> -i <sql file location> -o <output result file location>
Powershell.exe -executionpolicy remotesigned -File <location of powershell file>
The powershell file trigger an email when bat file is run.
Contents of powershell file
$smtpserver = "<smtp server name>"
$from="mail id"
$to="<mail id"
$a = Get-Date
$subject= "<subject line> `r"+ $a.Month +"/"+$a.Day +"/"+ $a.Year
$body=""
$attachment="File location"
Thanks,`n "
$mailer = new-object Net.Mail.SMTPclient($smtpserver)
$msg = new-object Net.Mail.MailMessage($from,$to,$subject,$body,$data1,$a)
$msg.IsBodyHTML = $true
$mailer.send($msg)
I use SQL Agent for send results via email like this:
/*
First you should set up SQL Mail Profile.
Please change #dbName, #SQLscript, #mailbody and mail account values. When changing your #SQLscript value be careful that replace (with CTRL+H) single quota (') to double quotas ('').
*/
DECLARE #dbName nvarchar(50), #SQLscript nvarchar(4000), #subject varchar(100), #mailfrom varchar(100), #mailbody nvarchar(4000), #jobName varchar(100)
SELECT #jobName = name from msdb..sysjobs where job_id = $(ESCAPE_NONE(JOBID))
SELECT #mailfrom = ##SERVICENAME + ' <' + cast(SERVERPROPERTY('ComputerNamePhysicalNETBIOS') as varchar(50)) + '#domain.com>'
SELECT #subject = N'SQL Server Job Result [Job: ' + #jobName + ']'
SELECT #dbName = 'Database'
SELECT #SQLscript = '
INSERT INTO [Database].[Schema].[Table] (
Column1
,Column2
) VALUES (
''Value1''
,''Value2'' )
'
SELECT #mailbody = N'
Depending on case number 1234-5678-90 your script executed on <b>' + ##SERVERNAME + N'</b> instance and <b>' + #dbName + '</b> database. Script info and results are shown below. <br><br>' +
'<b>Script: </b><br>' + #SQLscript + '<br><br>' +
'<b>Result: </b><br>'
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'sqlmailprofile',
#recipients = '<mail1#domain.com>;<mail2#domain.com>',
#copy_recipients = '<mail3#domain.com>',
#from_address = #mailfrom,
#reply_to = '<mail3#domain.com>',
#subject = #subject,
#body = #mailbody,
#body_format = 'HTML',
#importance = 'HIGH',
#execute_query_database = #dbName,
#query = #SQLscript
/* If you want to send results with attached file:
#attach_query_result_as_file = 1,
#query_attachment_filename = 'script_output.csv',
#query_result_separator=#tab,
#query_result_width =32767,
#query_result_no_padding=1,
#exclude_query_output=1,
#query_result_header=1
*/

set delimiter when using sp_send_dbmail (csv file)

I have a query that brings me back a result set but when I use sp_send_dbmailto send an email to someone containing this result set as a CSV file it opens in excel in the incorrect format! I know that I can correct this format through excel but I don't want the user to do that! I want them to just be able to open the file and everything be visible in the correct format. Below shows how I am creating the CSV file and emailing it out the someone (I am also specifying the seperator but it doesn't work and I can't figure out why):
EXEC msdb.dbo.sp_send_dbmail
#profile_name='TestProfile',
#recipients='Test#gmail.com',
#subject='Test message',
#body='This is a test.',
#query = 'Select firstName, LastName, Address, Score from TestData.dbo.Student',
#query_result_header = 0,
#exclude_query_output = 1,
#append_query_error = 1,
#attach_query_result_as_file = 1,
#query_result_separator = ',',
#query_result_width = 25,
#query_attachment_filename = 'Test.csv',
#query_result_no_padding = 1
Once the CSV File is received and opened all the data is represented in the first column, which isn't the desired results!
Screenshot of my list seperator settings
I struggled with this issue for a couple of days , but finally got it to work
#query_result_separator =' ', did the trick, it's TAB as the result separator.
Full code
EXEC msdb.dbo.sp_send_dbmail
#profile_name ='MailProfile',
#from_address = 'def#abc.com',
#recipients = 'Abc#abc.com',
#body = #varBody,
#body_format = 'HTML',
#execute_query_database ='MyDB',
#query = #VarSQL,
#attach_query_result_as_file = 1,
#query_result_separator =' ',
#exclude_query_output =1,
#query_result_no_padding=1,
#query_result_header =1,
#query_attachment_filename ='MyDB.csv'
If you are using Excel anyway, you can override Excel list separator and remove the problem all together, across every single regional setting out there.
Add the following line in the beginning of the CSV file: sep=;
In your example you would have this inside your #query.
..
#query_result_separator = ';',
#query = '
print ''sep=;''
SELECT 1,2'
..
Content of csv:
sep=;
1;2
Result; correct separation. Always!
You can't count on user regional settings or the application used to open the file.
Besides, any Excel user should know about Data->Text To Columns function.
The only thing you should take care of are fields that might contain the field separator (,) like addresses which should be wrapped with text qualifiers (e.g. ").
I think I could reproduce your issue with the data you provided. I found the answer in this superuser post.
It seems, Excel ignores your list separator if it is the same character as another already used character (for example decimal separator), it will work when you switch decimal separator to something else. But since you need this working on other client machines, too, you should consider switching to another csv-separator altogether (;?)

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.

Sending File through database Mail

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).