--用于测试的数据库:DBforTest
--Product:DBforTest数据库中的一张表
--ProductID,ProductName:Product表中的个字段名
--如果临时表已经存在,则将其删除
if exists(select * from DBforTest..sysobjects where id = object_id('DBforTest..TempTable'))
drop table DBforTest..TempTable
go
--根据需要导出的表的数据创建临时表,并将需要导出的表的所有字段名插入到第一行
select * into DBforTest..temptable from (
select 'ProductID' as [1],'ProductName' as [2]
Union all
SELECT convert(varchar,ProductID), convert(varchar,ProductName) FROM DBforTest..Product
) as temptable
--执行BCP命令,将临时表导出到指定的Excel文件中
EXEC master..xp_cmdshell 'bcp DBforTest..temptable out "E:/Product.xls" -c -q -S"192.168.0.21" -U"sa" -P"123"'
--删除临时表
drop table DBforTest..TempTable