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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM