sql 循環語句幾種方式

 

--第一
 
declare @orderNum varchar(255)
create table #ttableName(id int identity(1,1),Orders varchar(255))
declare @n int,@rows int
insert #ttableName(orders) select orderNum from pe_Orders where orderId<50
--select @rows=count(1) from pe_Orders
select @rows =@@rowcount 
set @n=1 
while @n<=@rows
begin
select @orderNum=OrderNum from PE_Orders where OrderNum=(select Orders from #ttableName where id=@n)
print (@OrderNum)
select @n=@n+1
end
drop table #ttableName
 
 
--第二
 
declare @orderN varchar(50)--臨時變量,用來保存遊標值
declare y_curr cursor for --申明遊標 爲orderNum
select orderNum from pe_Orders where orderId<50
open y_curr --打開遊標
fetch next from Y_curr into @orderN ----開始循環遊標變量
while(@@fetch_status=0)---返回被 FETCH  語句執行的最後遊標的狀態,而不是任何當前被鏈接打開的遊標的狀態。
begin
print (@orderN)
update pe_Orders set Functionary+@orderN where orderNum=@orderN --操做數據庫
fetch next from y_curr into @orderN --開始循環遊標變量
end
close 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=0
BEGIN TRAN --申明事務
declare @orderN varchar(50),@userN varchar(50) --臨時變量,用來保存遊標值
declare y_curr cursor for  --申明遊標 爲orderNum,userName
select orderNum,userName from PE_Orders where Orderid<50
open y_curr
fetch next from y_curr into @orderN,@userN
while @@fetch_status = 0
BEGIN
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,@userN
END
IF @error=0
BEGIN
commit tran --提交
END
ELSE
BEGIN
ROLLBACK TRAN --回滾
END
close y_curr
deallocate y_curr
DROP TABLE #t
 
-------------------------------------------------------------
轉自http://www.cnblogs.com/Luouy/archive/2012/05/11/2495394.html
相關文章
相關標籤/搜索