执行:
/****** Object: StoredProcedure [dbo].[ExportFile] Script Date: 2016-05-10 23:21:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
sp_configure 'show advanced options',1
reconfigure
go
sp_configure 'xp_cmdshell',1
reconfigure
go
Create PROC [dbo].[ExportFile]
@QuerySql VARCHAR(max)
,@Server VARCHAR(20)
,@User VARCHAR(20) = 'sa'
,@Password VARCHAR(20)
,@FilePath NVARCHAR(100) = 'd:\ExportFile.csv'
AS
DECLARE @tmp VARCHAR(50) = '[##Table' + CONVERT(VARCHAR(36),NEWID())+']'
BEGIN TRY
DECLARE @Sql VARCHAR(max),@DataSource VARCHAR(max)='';
--判断是否为远程服务器
IF @Server <> '.' AND @Server <> '127.0.0.1'
SET @DataSource = 'OPENDATASOURCE(''SQLOLEDB'',''Data Source='+@Server+';User ID='+@User+';Password='+@Password+''').'
--将结果集导出到指定的数据库
SET @Sql = REPLACE(@QuerySql,' from ',' into '+@tmp+ ' from ' + @DataSource)
PRINT @Sql
EXEC(@Sql)
DECLARE @Columns VARCHAR(max) = '',@Data NVARCHAR(max)=''
SELECT @Columns = @Columns + ',''' + name +''''--获取列名(xp_cmdshell导出文件没有列名)
,@Data = @Data + ',Convert(Nvarchar,[' + name +'])'--将结果集所在的字段更新为nvarchar(避免在列名和数据union的时候类型冲突)
FROM tempdb.sys.columns WHERE object_id = OBJECT_ID('tempdb..'+@tmp)
SELECT @Data = 'SELECT ' + SUBSTRING(@Data,2,LEN(@Data)) + ' FROM ' + @tmp
SELECT @Columns = 'Select ' + SUBSTRING(@Columns,2,LEN(@Columns))
--使用xp_cmdshell的bcp命令将数据导出
EXEC sp_configure 'xp_cmdshell',1
RECONFIGURE
DECLARE @cmd NVARCHAR(4000) = 'bcp "' + @Columns+' Union All ' + @Data+'" queryout ' + @FilePath + ' -c' + CASE WHEN RIGHT(@FilePath,4) = '.csv' THEN ' -t,' ELSE '' END + ' -T'
PRINT @cmd
exec sys.xp_cmdshell @cmd
EXEC sp_configure 'xp_cmdshell',0
RECONFIGURE
EXEC('DROP TABLE ' + @tmp)
END TRY
BEGIN CATCH
--处理异常
IF OBJECT_ID('tempdb..'+@tmp) IS NOT NULL
EXEC('DROP TABLE ' + @tmp)
EXEC sp_configure 'xp_cmdshell',0
RECONFIGURE
SELECT ERROR_MESSAGE()
END CATCH
调用:
EXEC dbo.ExportFile @QuerySql = 'select * from master.sys.objects', -- varchar(max)
@Server = '127.0.0.1', -- varchar(20)
@User = 'sa', -- varchar(20)
@Password = 'sa', -- varchar(20)
@FilePath = N'd:\ExportFile.csv' -- nvarchar(100)