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語句必須用單引號包含起來,語句中的原有單引號,需要使用兩個單引號替換(不是雙引號)。