sql server中嵌套游标的例子

发布时间:2020-04-04编辑:脚本学堂
本文介绍下,在sql server数据库中,使用嵌套游标的一个例子,学习下 sql server 游标cursor的用法,很不错的例子,供大家学习参考。

本节内容:
sql server游标的嵌套实例

sql语句,如下:
 

复制代码 代码示例:
--sql server 游标
declare @class varchar(30)
declare classcursor cursor for
select class from cmrtxl19.qifei.class where cmrtxl19.qifei.class.class like '%北京0609%'
open classcursor
fetch next from classcursor into @class
while ( @@fetch_status=0 ) 
begin
    print @class
    declare @username varchar(30)
    declare @userid varchar(30)
    declare classcursor_2 cursor for
    select 姓名,用户名 from pubs.qifei.bj0609fenban where 序号 is null and 班级名称=@class
    open classcursor_2
    fetch next from classcursor_2 into @username,@userid
    declare @i int
    set @i=1
    while ( @@fetch_status=0) 
    begin
        print '----'+@username+@userid
        if @i=1
        begin
            update cmrtxl19.qifei.class set adm = @username,admid = @userid
            where cmrtxl19.qifei.class.class = @class
        end
        else
        begin
            update cmrtxl19.qifei.class set adm2 = @username,adm2id = @userid
            where cmrtxl19.qifei.class.class = @class
        end
        set @i=@i+1
        if @i=3
        begin
            break
        end --// www.jb200.com
        fetch next from classcursor_2 into @username,@userid
    end                       
    close classcursor_2
    deallocate classcursor_2
    fetch next from classcursor into @class
end
close classcursor
deallocate classcursor