遊標變數用法經典

來源:互聯網
上載者:User
-- -產生測試表T
if   exists ( select   1   from  sysobjects  where  Name = N ' T '   and   objectProperty (ID,N ' IsUserTable ' ) = 1 )
     drop   table  T
go
select   top   5  ID,Name  into  T  from  sysobjects
go
方法1:

-- 建立輸出遊標變數的預存程序:

create   procedure  P_cursor(
                             @Roy_Test   cursor   varying  output
                        )
as

set   @Roy_Test = cursor  global  for
select  
    ID,Name
from  
    T
open   @Roy_Test
if   @@error <> 0
     return   1
go

-- 調用的預存程序:

create   procedure   P_cursor2
as
declare   @Roy_Test   cursor ,
         @ID   int , @Name  sysname

exec  P_cursor  @Roy_Test = @Roy_Test  output

IF   Cursor_Status ( ' variable ' ,  ' @Roy_Test ' )  <=   0
     return   1

fetch   next   from   @Roy_Test   into   @ID , @Name
while   @@fetch_status = 0
     begin
         print   ' ID= ' + rtrim ( @ID ) + ' ,Name= ' + @Name
         fetch   next   from   @Roy_Test   into   @ID , @Name
     end
close   @Roy_Test
deallocate   @Roy_Test
go


exec  P_cursor2         -- 查看結果

/**/ /*
ID=1,Name=sysobjects
ID=2,Name=sysindexes
ID=3,Name=syscolumns
ID=4,Name=systypes
ID=6,Name=syscomments

*/

go
create   procedure  P2_cursor( @Flag   bit )
as
declare   @roy_cursor   cursor ,
         @ID   int , @Name  sysname
if   @Flag = 0
     set   @roy_cursor = Roy_cursor
else
     return   1           -- 可以定義其它遊標
open   @roy_cursor
fetch   @roy_cursor   into   @ID , @Name

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.