游標的使用

2021-04-12 14:17:16 字數 2016 閱讀 9692

declare @sql varchar(8000), @password varchar(200)       --密碼  

,@tbname varchar(500)       --資料庫.dbo.表名,如果不指定:.dbo.表名,則匯出資料庫的所有使用者表  

,@filename   varchar(1000)     --匯入/匯出路徑/檔名,如果@tbname引數指明是匯出整個資料庫,則這個引數是檔案存放路徑,檔名自動用表名.xls  

,@isout   bit             --1為匯出,0為匯入

,@oid varchar(50) 

set @filename='c:/temp'; set @tbname='ppp;'; set @isout=1;

begin tran;  

if   @tbname   like   '%.%.%'   --如果指定了表名,則直接匯出單個表  

begin  

set   @sql='bcp  '+@tbname  

+case   when   @isout=1   then   '  out   '   else   '   in   '   end  

+'   "'+@filename+'"   /w'  

+'   /s   '+@@servername  

+'   /u   '+system_user 

+'   /p  ''+isnull(@password,'')'  

exec   master..xp_cmdshell   @sql  

end  

else  

begin   --匯出整個資料庫,定義游標,取出所有的使用者表

declare   @m_tbname   varchar(250)  

if   right(@filename,1)<>'/'  set   @filename=@filename+'/'  

set   @m_tbname='declare   #tb   cursor   for   select   name   from   '+@tbname+'..sysobjects   where   xtype=''u'''  

exec(@m_tbname)  

open   #tb  

fetch   next   from   #tb   into   @m_tbname  

while   @@fetch_status=0  

begin 

set   @sql='bcp   '+@tbname+'..'+@m_tbname  

+case   when   @isout=1   then  '   out   '   else   '   in   '   end  

+'   "'+@filename+@m_tbname+'.xls   "   /w'  

+'   /s   '+@@servername  

+'   /u   '+'sa'  

+'   /p   '+isnull(@password,'')  

exec   master..xp_cmdshell   @sql  

fetch   next   from   #tb   into   @m_tbname  

end  

close   #tb  

deallocate   #tb    

endif(@isout=1)

begin

declare @opname varchar(50);

set @opname=(select usr_login from ucml_user where ucml_useroid=@oid);  

insert into systemoprating(systemopratingoid,bakdate,opname,ucml_user_fk)values(newid(),getdate(),@opname,@oid);

endcommit tran; 

游標的使用

游標 cursor 是處理資料的一種方法,為了檢視或者處理結果集中的資料,游標提供了在結果集中一次以行或者多行前進或向後瀏覽資料的能力。我們可以把游標當作乙個指標,它可以指定結果中的任何位置,然後允許使用者對指定位置的資料進行處理。1.游標的組成 游標包含兩個部分 乙個是游標結果集 乙個是游標位置。...

游標的使用

use newsite go object storedprocedure dbo pro cutpoint script date 04 21 2011 10 49 16 set ansi nulls on goset quoted identifier on goalter procedure ...

游標的使用

declare userid varchar 20 將 temp2 值賦給當前游標 declare c getdata cursor forselect userid from temp2 開啟當前游標 並將游標值賦給變數 open c getdata fetch c getdata into us...