DECLARE @x nvarchar (100)
set @x= ‘商品清单 ‘
--执行存储过程,生成CSV文件
EXEC [dbo]. [UP_Export_Data_To_CSV]
@Table=‘[db01].dbo.[View_GoodsInfo]‘ ,--指定的视图数据
@Path=‘d:\DataReport\‘ ,
@Subfix=@x ,
@Server=‘.‘ ,
@User=‘sa‘ ,
@Password=‘1111‘
DECLARE @s nvarchar (100)
DECLARE @b nvarchar (MAX)
DECLARE @c1 nvarchar (255)
DECLARE @c2 nvarchar (255)
DECLARE @c nvarchar (MAX)
--SQL Mail邮件发送
SELECT @s = N‘商品清单 _‘+CONVERT (varchar( 10),GETDATE (),120)
SELECT @b = N‘Hi All,
附件为截止至 (‘+CONVERT (varchar( 10),GETDATE (),120 )+ ‘ ‘
+N‘)的数据,请知晓! ‘
SELECT @c1 = N‘d:\DataReport\‘+ CONVERT(varchar (10), GETDATE(),120 )
+N‘_商品清单 csv‘
SELECT @c = @c1
EXEC msdb. dbo.sp_send_dbmail @profile_name = ‘aa‘, --SQL Mail中配置的名称
@recipients = ‘tony@sina.com;‘ ,
@copy_recipients = ‘eva@sina.com;‘ ,
@blind_copy_recipients = ‘milk@sina.com;‘ ,
@body =@b ,
@subject = @s,
@file_attachments = @c
--创建存储过程,生成CSV文件导出
CREATE PROCEDURE [dbo].[UP_Export_Data_To_CSV]
@Table NVARCHAR( 255),
@Path NVARCHAR( 255),
@Subfix NVARCHAR( 50),
@Server VARCHAR( 20),
@User VARCHAR( 20),
@Password VARCHAR( 50)
AS
BEGIN
DECLARE @SQL NVARCHAR (2000)
DECLARE @File NVARCHAR (255)
IF (LEN (ISNULL( @Path,‘‘ ))>0)
BEGIN
SELECT @File= @Path+‘\‘
END
--确定文件后缀
SELECT @File= @File+Convert ( VARCHAR(10 ),GETDATE(), 120)+‘_‘
+CAST( DATEPART(HOUR ,GETDATE()) as nvarchar(2 ))
IF (LEN (ISNULL( @Subfix,‘‘ ))>0)
BEGIN
SELECT @File= @File+‘_‘ +@Subfix
END
SELECT @File= @File+‘.csv‘
--使用BCP 命令
SELECT @SQL = N‘bcp ‘+ @Table+‘ out ‘ +@File+ ‘ -c -t, -T -S‘
+@Server +‘ -U‘+@User+ ‘ -P ‘+@Password
EXEC master ..xp_cmdshell @SQL
END