SQL Server 2005使用BCP命令将数据表导出到Excel第一行包括表头

--首选需要确保已经启用xp_cmdshell --启用命令如下,也可以通过外围应用程序配置器启用

-------------------------------------------------------------------------------

-- 允许配置高级选项 EXEC sp_configure 'show advanced options', 1 GO

-- 重新配置 RECONFIGURE GO

-- 启用xp_cmdshell ,如果要禁用,这将这个命令的1改为0 EXEC sp_configure 'xp_cmdshell', 1 GO

--重新配置 RECONFIGURE GO

-------------------------------------------------------------------------------

--用于测试的数据库:wm20130428--bs_sellerFile:wm20130428数据库中的一张表 --SellerCode,SellerName:bs_sellerFile表中的个字段名

--如果临时表已经存在,则将其删除

if exists(select * from wm20130428..sysobjects where id = object_id('wm20130428..TempTable'))

drop table wm20130428..TempTable

go

--根据需要导出的表的数据创建临时表,并将需要导出的表的所有字段名插入到第一行

select * into wm20130428..temptable from (

select 'SellerCode' as [1],'SellerName' as [2]

Union all

SELECT convert(varchar,SellerCode), convert(varchar,SellerName) FROM wm20130428..bs_sellerFile

) as temptable

--执行BCP命令,将临时表导出到指定的Excel文件中

--EXEC master..xp_cmdshell 'bcp"select SellerCode,SellerName wm20130428..bs_sellerFile" queryout  "C:/Product.xls" -c -q -S"192.168.1.110" -U"sa" -P"sa"'

EXEC master..xp_cmdshell 'BCP "SELECT top 20 * FROM wm20130428..temptable" queryout "c:\currency2.xls" -c -q -S"192.168.1.110" -U"sa" -P"sa"' --删除临时表 drop table wm20130428..TempTable

posted @ 2013-05-20 18:19  Net学者  阅读(3273)  评论(0编辑  收藏  举报