sql server 存储过程---游标的循环


sqlserver中的循环遍历(普通循环和游标循环)

sql 经常用到循环,下面介绍一下普通循环和游标循环

1、首先需要一个测试表数据Student

2、普通循环

1)循环5次来修改学生表信息

--循环遍历修改记录--
declare @i int   
set @i=0
while @i<5
begin
    update Student set demo = @i+5 where Uid=@i
    set @i=@i +1 
end
--查看结果--
select * from Student

2)执行后的查询结果

3、游标循环(没有事务)

1)根据学生表实际数据循环修改信息
---游标循环遍历--
begin
    declare @a int,@error int    
    declare @temp varchar(50)
    set @a=1
    set @error=0
    --申明游标为Uid
    declare order_cursor cursor 
    for (select [Uid] from Student)
    --打开游标--
    open order_cursor
    --开始循环游标变量--
    fetch next from order_cursor into @temp
    while @@FETCH_STATUS = 0    --返回被 FETCH语句执行的最后游标的状态--
        begin            
            update Student set Age=15+@a,demo=@a where Uid=@temp
            set @a=@a+1
            set @error= @error + @@ERROR   --记录每次运行sql后是否正确,0正确
            fetch next from order_cursor into @temp   --转到下一个游标,没有会死循环
        end    
    close order_cursor  --关闭游标
    deallocate order_cursor   --释放游标
end
go
--查看结果--
select * from Student

2)执行后的查询结果

4、游标循环(事务)

1)根据实际循环学生表信息

---游标循环遍历--
begin
    declare @a int,@error int    
    declare @temp varchar(50)
    set @a=1
    set @error=0
    begin tran  --申明事务
    --申明游标为Uid
    declare order_cursor cursor 
    for (select [Uid] from Student)
    --打开游标--
    open order_cursor
    --开始循环游标变量--
    fetch next from order_cursor into @temp
    while @@FETCH_STATUS = 0    --返回被 FETCH语句执行的最后游标的状态--
        begin            
            update Student set Age=20+@a,demo=@a where Uid=@temp
            set @a=@a+1
            set @error= @error + @@ERROR   --记录每次运行sql后是否正确,0正确
            fetch next from order_cursor into @temp   --转到下一个游标
        end    
    if @error=0
    begin
        commit tran   --提交事务
    end
    else
    begin
        rollback tran --回滚事务
    end
    close order_cursor  --关闭游标
    deallocate order_cursor   --释放游标
end
go
--查看结果--
select * from Student

2)执行后的查询结果:


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM