几种游标的用法(游标的几种使用方法)

/ 0评 / 0

几种游标的用法(游标的几种应用办法)

应用游标变量赋值

use TestSchool

go

declare @varcursor Cursor --声明游标变量

declare cursor_Adress cursor for --创立游标

select Id,PCity ,Pcode from Adress;

open cursor_Adress; --打开游标

set @varcursor = cursor_Adress --为游标变量赋值

fetch next from @varcursor --从游标变量中读取值

wh百思特网ile @@FETCH_STATUS = 0 --断定fetch 语句是否履行胜利

begin

fetch next from @varcursor --读取游标变量中的数据

end

close @varcursor --关闭游标

deallocate @varcursor --释放游标

成果:

用order by 子句转变游标中行的次序

--用order by 子句转变游标中行的次序

use TestSchool

go

declare Curs百思特网or_Order cursor for

select Id,PCity from Adress

order by Id desc

open Cursor_Order

fetch next from Cursor_Order

while @@FETCH_STATUS = 0

fetch next from Cursor_Order

close Cursor_Order

deallocate Cursor_Order;

成果:

应用游标修正数据

--应用游标修正数据use TestSchoolselect * from newtablego&nb百思特网sp;declare @Cid int declare @Id int = 17declare Cursor_Alter cursor forselect Cid from newtable ;open Cursor_Alter fetch next from Cursor_Alter into @Cidwhile @@FETCH_STATUS = 0 begin if @Cid = @Id begin update newtable set CName = '025班' where Cid = @Idendfetch next from Cursor_Alter into @Cid endclose Cursor_Alterdeallocate Cursor_Alterselect * from newtable where Cid = 17;

成果:

应用游标删除数据

--应用游标删除数据

use TestSchool

insert into newtable values (13 ,'022班 ')

select * from newtable

go

declare @Cid int

declare @Id int = 13

declare Cursor_Delete cursor for

select Cid from newtable ;

open Cursor_Delete

fetch next from Cursor_Delete into @Cid

while @@FETCH_STATUS = 0

begin

if @Cid = @Id

begin

delete from newtable where Cid = @Id

end

fetch next from Cursor_Delete into @Cid

end

close Cursor_Delete

deallocate Cursor_Delete

select * from newtable

成果: