您的位置:首页 > 数据库

sql 循环语句几种方式

2012-05-11 09:19 363 查看
--第一
declare @orderNum varchar(255)create table #ttableName(id int identity(1,1),Orders varchar(255))declare @n int,@rows intinsert #ttableName(orders) select orderNum from pe_Orders where orderId<50--select @rows=count(1) from pe_Ordersselect @rows =@@rowcount set @n=1 while @n<=@rowsbegin select @orderNum=OrderNum from PE_Orders where OrderNum=(select Orders from #ttableName where id=@n) print (@OrderNum) select @n=@n+1enddrop table #ttableName

--第二
declare @orderN varchar(50)--临时变量,用来保存游标值declare y_curr cursor for --申明游标 为orderNumselect orderNum from pe_Orders where orderId<50open y_curr --打开游标fetch next from Y_curr into @orderN ----开始循环游标变量while(@@fetch_status=0)---返回被 FETCH 语句执行的最后游标的状态,而不是任何当前被连接打开的游标的状态。beginprint (@orderN) update pe_Orders set Functionary+@orderN where orderNum=@orderN --操作数据库fetch next from y_curr into @orderN --开始循环游标变量endclose y_curr--关闭游标deallocate y_curr --释放游标
--第三select orderNum,userName,MoneyTotal into #t from pe_Orders po DECLARE @n int,@error int--set @n=1 set @error=0BEGIN TRAN --申明事务declare @orderN varchar(50),@userN varchar(50) --临时变量,用来保存游标值declare y_curr cursor for --申明游标 为orderNum,userNameselect orderNum,userName from PE_Orders where Orderid<50open y_currfetch next from y_curr into @orderN,@userNwhile @@fetch_status = 0BEGIN select isnull(sum(MoneyTotal),0),orderNum from #t where username=@userN-- set @n=@n+1 set @error=@error+@@error--记录每次运行sql后 是否正确 0正确 fetch next from y_curr into @orderN,@userNENDIF @error=0 BEGIN commit tran --提交 ENDELSE BEGIN ROLLBACK TRAN --回滚 ENDclose y_currdeallocate y_currDROP TABLE #t
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: