--首選需要確保已經啟用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