简体   繁体   中英

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
*/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM