SQL Server 游标使用

create procedure Demo
as
begin
    declare @tmpID int,@tmpName varchar(12);
    begin try
        -- 注意:有order by不能对select 语句使用括号
        declare cr cursor for select ID,UserName from #tmp order by ID; 
        open cr;
        fetch next from cr into @tmpID,@tmpName;
           -- @@fetch_status 返回当前打开的游标的 FETCH 语句的状态
        while(@@fetch_status=0)
        begin
           print convert(varchar(6),@tmpID) + @tmpName;
           fetch next from cr into @tmpID,@tmpName; --读取下一条数据
           if(@tmpName = 'aabb') goto userGO;
        end;

        userGO: print '自定义GOTO语句跳转';

        close cr;       -- 关闭游标
        deallocate cr;  -- 释放游标
    end try
    begin catch   
        close cr;       -- 关闭游标
        deallocate cr;  -- 释放游标
        print '异常处理!'
    end catch
end;

 

posted @ 2018-03-26 11:24  都是城市惹的祸  阅读(89)  评论(0)    收藏  举报