BCP xp_cmdshell

SQL Server 数据导出技巧
本文详细介绍如何使用SQL Server的xp_cmdshell存储过程配合BCP命令,从现有表及全局临时表导出数据到Excel文件的方法。同时,文章还探讨了在导出过程中可能遇到的错误及其解决方案,例如双引号与查询语句之间的空格问题。

---------------------- 从现有表导出结果 ----------------------
-- 将AdventureWorks.HumanResources.Employee表的数据导出到C:\test.xls
EXEC master..xp_cmdshell ' BCP "select * from AdventureWorks.HumanResources.Employee" queryout C:\test.xls -c  -SCN110075 -Usa -Pchang' 

-- 删除C:\test.xls
EXEC master..xp_cmdshell 'del C:\test.xls '

---------------------- 从全局临时表表导出结果 ----------------------
-- 建立临时表
select row_number() over(order by employeeId) as rowNumber, * into ##tmp from AdventureWorks.HumanResources.Employee

-- 从临时表导出数据
EXEC master..xp_cmdshell ' BCP "select * from tempdb..##tmp " queryout C:\test.xls -c  -SCN110075 -Usa -Pchang' 

-- 删除临时表
drop table ##tmp

-- 删除C:\test.xls
EXEC master..xp_cmdshell 'del C:\test.xls '

---------------------- 这样写有错,还为找到原因 ----------------------
EXEC master..xp_cmdshell ' BCP "HumanResources.Employee " out C:\test.xls -c  -SCN110075 -Usa -Pchang' 

-- 错误信息
/*
output
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
An error occurred while processing the command line.
NULL
*/

---------------------- union 好像双引号与查询语句之间不能有空格 ----------------------
EXEC master..xp_cmdshell 'BCP " select
"''ForeCastType''" as ForeCastType, "''OrderNumber''" as OrderNumber,
"''HHPN''" as HHPN, "''Plant''" as Plant, "''Quantity''" as Quantity, "''DueDate''" as DueDate
union
select "''LSF''" as ForeCastType, "''FCST2006''" as OrderNumber, HHPN,  Plant,
convert(varchar(10),Quantity) as Quantity, convert(char(10), DueDate, 20) as DueDate 
from Converter.dbo.detail
where pid=1 order by plant, HHPN, DueDate "
queryout c:\output.xls -c -SCN110075 -Usa -Pchang'

转载于:https://www.cnblogs.com/aspsmile/archive/2008/08/05/1260782.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值