sqlserver 游标的使用

时间:2021-08-22 15:27:47
declare @temp_temp uniqueidentifier--临时变量
DECLARE aaa CURSOR for select Id from A
-------------------打开游标
open aaa
--先查询一次再循环,防止有多个游标时@@FETCH_STATUS=-1不能进入下个游标循环的情况
fetch next from aaa into @temp_temp
-------------------循环取数据
while @@FETCH_STATUS=0
begin
print @temp_temp
fetch next from aaa into @temp_temp end
----------------------------------- 关闭游标
Close aaa
----------------------------------- 删除游标
Deallocate aaa

  

游标的嵌套

declare @temp_temp uniqueidentifier--临时变量
DECLARE aaa CURSOR for select Id from A
-------------------打开游标
open aaa
--先查询一次再循环,防止有多个游标时@@FETCH_STATUS=-1不能进入下个游标循环的情况
fetch next from aaa into @temp_temp
-------------------循环取数据
while @@FETCH_STATUS=0
begin
print @temp_temp
--===========================游标嵌套
DECLARE bbb CURSOR for select Id from B
-------------------打开游标
open bbb
--先查询一次再循环,防止有多个游标时@@FETCH_STATUS=-1不能进入下个游标循环的情况
fetch next from bbb into @temp_temp
-------------------循环取数据
while @@FETCH_STATUS=0
begin
print @temp_temp
fetch next from bbb into @temp_temp end
----------------------------------- 关闭游标
Close bbb
----------------------------------- 删除游标
Deallocate bbb
--===========================游标嵌套
fetch next from aaa into @temp_temp end
----------------------------------- 关闭游标
Close aaa
----------------------------------- 删除游标
Deallocate aaa