1.将数据库中查询的表格导出到指定的路径,首先启用.xp_cmdshell,上一篇随笔有写如何开启.xp_cmdshell。
declare @sql nvarchar(4000) –定义变量存储格式
declare @server nvarchar(20) –定义变量存储格式
set @server=’localhost’ –赋值变量
declare @filename1 nvarchar(max) –定义变量存储格式
set @filename1=’d:\\gsfiles\\hrleave\\monthstat\\gsot_weekrep_’+convert(nvarchar,getdate(),112)+’.xls’ –赋值变量路径
set @sql= ‘bcp “select adays,empid,empname,thour3,deptid,deptname from gseservicedb.dbo.gsot_alarm_day002_total” queryout ‘+@filename1+’ -c -w -s ‘+@server+’ -t ‘ –使用bcp queryout sql语句导出数据库表存储到本地
exec master..xp_cmdshell @sql –执行@sql 的bcp命令
2.将存储本地的excel用邮件方式发送
exec msdb.dbo.sp_send_dbmail
@profile_name=’mis_ebiz’,
@recipients=’邮件地址’,
@copy_recipients=”,
@blind_copy_recipients=”,
@subject=”,
@body=”,
@body_format=’html’, –传送格式语言
@file_attachments =@filename1; –带入赋值变量存储的路径文件(附件)