需求:分页方式查出表中数据存入excel中,并给excel标记不同的编号
前提: #all_4表中数据已准备好
版本: sql server 2008
declare @n int
set @n = 1
while @n = 100
begin
print '@n:'
print @n
EXEC master.dbo.sp_configure 'show advanced options', 1
RECONFIGURE
EXEC master.dbo.sp_configure 'xp_cmdshell', 1
RECONFIGURE
declare @fileName varchar(128)
set @fileName ='D:\文件-' + cast( @n as varchar) +'.xls'
IF OBJECT_ID('master..t_msg') IS NOT NULL
drop table master..t_msg
select user_id 账号ID, date 时间, in_amount 总积分 ,description 描述, from_user 送礼人ID,
注册时间, 三方账号类型, 三方账号, 姓名, 身份证号, 手机号
into master..t_msg
from (
select * ,row_number() over (order by user_id ,date ) rn
from #all_4
)t
where rn
between 950000*(@n-1)+1 and 950000*(@n)
declare @sql varchar(8000)
set @sql = 'bcp "SELECT ''账号ID'' as 账号ID,''时间'' as 时间,''总积分'' as 总积分,''描述'' as 描述 ,''送礼人ID'' as 送礼人ID,''注册时间'' as 注册时间 ,''三方账号类型'' as 三方账号类型 ,''三方账号'' as 三方账号,''姓名'' as 姓名 ,''身份证号'' as 身份证号,''手机号'' as 手机号 union all SELECT cast(账号ID as varchar),cast(时间 as varchar),cast(总积分 as varchar),cast(描述 as varchar), cast(送礼人ID as varchar), cast(注册时间 as varchar),cast(三方账号类型 as varchar) ,cast(三方账号 as varchar) ,cast(姓名 as varchar) ,cast(身份证号 as varchar) ,cast(手机号 as varchar) FROM master..t_msg " queryout " '+@fileName + '" -c -T '
EXEC master..xp_cmdshell @sql
EXEC master.dbo.sp_configure 'xp_cmdshell', 0
RECONFIGURE
EXEC master.dbo.sp_configure 'show advanced options', 0--配置选项 (bcp用法及高级选项)
RECONFIGURE
end
报错信息:Error = [Microsoft][SQL Server Native Client 10.0]无法打开 BCP 主数据文件
报错信息所指步骤:数据存入excel文件
猜测原因:1、select 语句拼错 2、要存入的文件是打开状态
定位问题方法:将拼接的sql打印出来,与能正常运行的代码比对
最终定位具体原因:文件名是用双引号括起来的,而拼sql时多出了个空格,非常细节的一个问题
错误部分代码修正:
set @sql = 'bcp "SELECT ''账号ID'' as 账号ID,''时间'' as 时间,''总积分'' as 总积分,''描述'' as 描述 ,''送礼人ID'' as 送礼人ID,''注册时间'' as 注册时间 ,''三方账号类型'' as 三方账号类型 ,''三方账号'' as 三方账号,''姓名'' as 姓名 ,''身份证号'' as 身份证号,''手机号'' as 手机号 union all SELECT cast(账号ID as varchar),cast(时间 as varchar),cast(总积分 as varchar),cast(描述 as varchar), cast(送礼人ID as varchar), cast(注册时间 as varchar),cast(三方账号类型 as varchar) ,cast(三方账号 as varchar) ,cast(姓名 as varchar) ,cast(身份证号 as varchar) ,cast(手机号 as varchar) FROM master..t_msg " queryout "'+@fileName + '" -c -T '
完美解决~