sqlserver 循环遍历 游标 事务

以a_1表 循环 插入 b_1 表为例

 

 

1.普通的循环 插入a_1表

--一个正常的循环 指定30次 插入数据
declare @i int
set @i=1
while @i<30
begin 
	insert into a_1(a)values(@i)
set @i=@i+1
end

  

2.循环a_1表 然后游标插入b_1表数据.    加了一个 temp2 一个表两个字段的情况下

 

--循环表 然后游标插入另一个表数据
begin
    declare @error int
    declare @temp varchar(50)
   declare @temp2 varchar(50)
set @error=0 --申明游标 declare order_cursor cursor for(select a,a1 from a_1) open order_cursor --打开游标 --取出一条数据 赋值给@temp,开始循环游标 fetch next from order_cursor into @temp,@temp2 --开始循环语句 while @@FETCH_STATUS=0 --查看状态 返回被 fetch 语句执行的最后游标的状态 begin insert into b_1(b,c)values(@temp,@temp2) --开始插入数据 print(@temp) set @error=@error+@@ERROR --记录语句运行是否正确 0正确 fetch next from order_cursor into @temp,@temp2 --取出下一条数据 赋值给@temp,继续循环 end close order_cursor --关闭游标 deallocate order_cursor --释放游标 end

 

3. 加入事务 循环a_1表 然后游标插入b_1表数据.

begin
    declare @a int,@error int
    declare @temp varchar(50)
    set @a=1
    set @error=0
    begin tran --申明事务
    declare order_cursor cursor for(select a from a_1) --申明游标
    open order_cursor --打开游标
    fetch next from order_cursor into @temp   --取出一条数据 赋值给@temp,开始循环游标
    --开始循环语句
    while @@FETCH_STATUS=0 --查看状态 返回被 fetch 语句执行的最后游标的状态
        begin
            insert into b_1(b)values(@temp)  --开始插入数据
            print(@temp)
            set @error=@error+@@ERROR --记录语句运行是否正确 0正确
            fetch next from order_cursor into @temp  --取出下一条数据 赋值给@temp,继续循环
        end

    if @error=0
    begin
        commit tran   --提交事务
    end
    else
    begin
        rollback tran --回滚事务
    end
    close order_cursor --关闭游标
    deallocate order_cursor    --释放游标
end
go
--查看结果
select * from b_1

 

来源:

www.ailone.vip

 

posted @ 2023-07-21 15:45  荧屏  阅读(436)  评论(0编辑  收藏  举报