sqlserver利用存储过程批量导出excel

begin
DECLARE @shenfenzheng VARCHAR(20)
declare @file_path varchar(200);--导出EXCEl文件的路径;
declare @file_name varchar(200);--导出EXCEl的文件名;
declare @exec_sql  varchar(8000);--SQL语句;
declare @exec_sql2 varchar(8000);--SQL语句;

set @file_path = 'C:\123\'

DECLARE order_cursor CURSOR 
FOR SELECT cardnum FROM mdjhz.dbo.dealngUser
OPEN order_cursor
fetch next from order_cursor into @shenfenzheng
while @@fetch_status<>-1
IF ISNULL(@shenfenzheng,'')<>''
begin
set @file_name = @shenfenzheng+'.xls'
set @exec_sql = 'select CONVERT(varchar(10),V.Vouchdate,120) ''日期'',D.dealuserName ''客户'',''''''''+D.cardnum ''身份证号'',D.address,D.jyxm,(select username from mdzjhz.dbo.tbuser2 u2 where u2.userlogo2=v.dealingcharacterid) ''组织机构'',(select VouchTypename from mdzjhz.dbo.VouchType where VouchTypeID=V.VouchTypeID) as ''单证类型'',(select operationname from mdzjhz.dbo.operationtype where operationlogo=v.operationid) ''业务明细'' ,V.principal ''金额'',(select statename from mdzjhz.dbo.Vouchstate where state=V.state) as ''状态'' , V.creditVouchID ''单证编号'',V.creditoperationID ''业务编码'',''''''''+V.bankAccount ''卡号'' from mdzjhz.dbo.creditVouch V,mdzjhz.dbo.dealingUser D where V.dealinglogo=D.dealuserlogo and V.state <>0 and ((V.VouchDate >='''' or ''''='''') and (V.VouchDate <'''' or ''''='''')) and V.creditVouchID like ''%%'' and V.creditoperationID LIKE ''%%''  and ((select statename from mdzjhz.dbo.Vouchstate where state=V.state) = ''--显示全部--'' or ''--显示全部--''=''--显示全部--'')    and ((select VouchTypename from mdzjhz.dbo.VouchType where VouchTypeID=V.VouchTypeID) = ''--显示全部--'' or ''--显示全部--''=''--显示全部--'') and ((select operationname from mdzjhz.dbo.operationtype where operationlogo=v.operationid)= ''--显示全部--'' or ''--显示全部--''=''--显示全部--'') and (D.cardnum like '''+@shenfenzheng+''') and ((select officename from mdzjhz.dbo.office where officelogo=V.officelogo)=''--显示全部--'' or ''--显示全部--''=''--显示全部--'')  and isnull((select username from mdzjhz.dbo.tbuser2 u2 where u2.userlogo2=v.dealingcharacterid),'''') like ''%%''  order by V.VouchDate'
set @exec_sql2 = ' bcp "'+@exec_sql+'" queryout "'+@file_path+''+@file_name+'" -c -T -S "PC-2020030906\DDD" -U "sa" -P "123456"';
exec master..xp_cmdshell @exec_sql2
---waitfor time '0:0:1'
fetch next from order_cursor into @shenfenzheng
---waitfor delay '0:0:0.5'
end
else
begin
fetch next from order_cursor into @shenfenzheng
end
close order_cursor
deallocate order_cursor
end
go

总结:

1、因为C盘为固态硬盘,写入速度应该快,其实经过测试并没发现快。写入c盘的话,需要把赋予everyone的文件夹写权限。

2、cardnum查询出来的身份证号码有40000+,写excel时,到了900多条ssms就卡死了。不知道啥原因。

3、第一次用存储过程,sql语句必须用单引号包含起来,语句中的原有单引号,需要使用两个单引号替换(不是双引号)。

posted @ 2020-06-10 11:26  B1gstar  阅读(943)  评论(0编辑  收藏  举报