SQL 游标的使用




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

打赏

取消 我去学网

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,你说多少就多少
微信

打开微信扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

  1. #2

    木庄网络博客(2016/10/28 11:41:03)
    不错的网站主题,看着相当舒服

  2. #1

    木庄网络博客(2016/10/14 21:02:39)
    博客做得好漂亮哦!