Heim >Datenbank >MySQL-Tutorial >SQL表中数据按条件批量导出多个Excel文件

SQL表中数据按条件批量导出多个Excel文件

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-06-07 16:17:362840Durchsuche

SQL Server表中数据按条件批量导出为多个Excel文件是本文我们主要要介绍的内容,在一次SQL Server数据库的操作中,需要将某个有数十万行数据的表按类别导出为xls文件,每个类别一个xls。将数据表中的数据导出并保存为xls简单,用 SSIS或者查询出来之后另存为

  SQL Server表中数据按条件批量导出为多个Excel文件是本文我们主要要介绍的内容,在一次SQL Server数据库的操作中,需要将某个有数十万行数据的表按类别导出为xls文件,每个类别一个xls。将数据表中的数据导出并保存为xls简单,用 SSIS或者查询出来之后另存为都可以。但是,,这个表中的分类有数百个,如果一个个用SSIS或者查询另存为的话,工作量巨大。前思后想,想到了用 while循环查询,并用bcp导出的方法。

  下面是相关代码:

--声明需要的变量
declare @sql varchar(600),@TypeID int
--确认第一个分类的ID
select @TypeID=min(TypeID) from t_TestTable
--当存在满足分类ID的记录时进行处理
while exists(select 1 from t_TestTable where TypeID=@TypeID)
begin
--拼凑需要执行的语句
set @sql='bcp "select * from (select'+'''列名1'''+' AS 列名1,'+'''列名2'''+' AS 列名2,'+'''列名3'''+' AS 列名3'--在xls文件中显示列名
set @sql=@sql+' union all select 列名1,列名2,列名3 from t_TestTable where TypeID='+cast(@TypeID as varchar(8))+')a" queryout "F:datafileTypeData'+cast(@TypeID as varchar(8))+'.xls" -c -q -S"ServerName" -U"sa" -P"SAPASSWORD" -d"DBName"'--查询满足条件的记录并保存到xls文件中
--使用xp_cmdshell系统存储过程执行拼凑好的语句(需要使用高级选项开关预先开启cmdshell组件)
exec master..xp_cmdshell @sql
--获得下一个分类的ID(分类ID是不连续的)
select @TypeID=isnull(min(TypeID),@TypeID+1) from t_TestTable where TypeID>=@TypeID+1
end

以上就是SQL Server表中数据按条件批量导出为多个Excel文件的实现方法,本文就介绍到这里了,希望本次的介绍能够对您有所收获!
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn