sql 循环语句几种方式(变量循环,游标循环,事务)

--第一
 
 1 declare @orderNum varchar(255)
 2 create table #ttableName(id int identity(1,1),Orders varchar(255))
 3 declare @n int,@rows int
 4 
 5 
 6 insert #ttableName(orders) select orderNum from FOrders where orderId<50
 7 --select @rows=count(1) from pe_Orders
 8 select @rows =@@rowcount 
 9 set @n=1 
10 while @n<=@rows
11   begin
12     select @orderNum=OrderNum from PE_Orders where OrderNum=(select Orders from #ttableName where id=@n)
13     print (@OrderNum)
14     select @n=@n+1
15   end
16 drop table #ttableName
View Code

 

--第二
 1 declare @tmp varchar(50)--临时变量,用来保存游标值
 2 declare y_curr cursor for --申明游标 为orderNum
 3 select orderNum from FOrders where orderId<50
 4 open y_curr --打开游标
 5 fetch next from Y_curr into @tmp ----开始循环游标变量
 6 while(@@fetch_status=0)---返回被 FETCH 语句执行的最后游标的状态,而不是任何当前被连接打开的游标的状态。
 7   begin
 8     print (@tmp)
 9     update FOrders set Functionary+@tmp where orderNum=@tmp --操作数据库
10     fetch next from y_curr into @tmp --开始循环游标变量
11   end
12 close y_curr--关闭游标
13 deallocate y_curr --释放游标

 

--第三

 1 select orderNum,userName,MoneyTotal into #t from FOrders po 
 2 DECLARE @n int,@error int
 3 --set @n=1 
 4 set @error=0
 5   BEGIN TRAN --申明事务
 6     declare @tmp varchar(50),@userN varchar(50) --临时变量,用来保存游标值
 7     declare y_curr cursor for --申明游标 为orderNum,userName
 8     select orderNum,userName from FOrders where Orderid<50
 9     open y_curr
10     fetch next from y_curr into @tmp,@userN
11     while @@fetch_status = 0
12       BEGIN
13         select isnull(sum(MoneyTotal),0),orderNum from #t where username=@userN
14         -- set @n=@n+1
15         set @error=@error+@@error--记录每次运行sql后 是否正确 0正确
16         fetch next from y_curr into @tmp,@userN
17       END
18     IF @error=0
19     BEGIN
20   commit tran --提交
21 END
22 ELSE
23   BEGIN
24     ROLLBACK TRAN --回滚
25   END
26 close y_curr
27 deallocate y_curr
28 DROP TABLE #t

 

 

posted on 2018-12-13 22:21  绅士狼  阅读(564)  评论(0编辑  收藏  举报

导航