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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM