1. 程式人生 > >sql 迴圈語句幾種方式(變數迴圈,遊標迴圈,事務)

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 FOrders where orderId<50 --select @rows=count(1) from pe_Orders select @rows [email protected]@rowcount set @n=1 while @n<
[email protected]
  begin     select @orderNum=OrderNum from PE_Orders where OrderNum=(select Orders from #ttableName where [email protected])     print (@OrderNum)     select @[email protected]+1   end drop table #ttableName
 

 

    --第二    
declare @tmp varchar(50)--臨時變數,用來儲存遊標值
declare y_curr cursor for --申明遊標 為orderNum
select orderNum from FOrders where orderId<50
open y_curr --開啟遊標
fetch next from Y_curr into @tmp ----開始循環遊標變數
while(@@fetch_status=0)---返回被 FETCH 語句執行的最後遊標的狀態,而不是任何當前被連線開啟的遊標的狀態。
  begin
    print (@tmp)
    update FOrders set 
[email protected]
where [email protected] --操作資料庫     fetch next from y_curr into @tmp --開始循環遊標變數   end close y_curr--關閉遊標 deallocate y_curr --釋放遊標
 

 

--第三

 
select orderNum,userName,MoneyTotal into #t from FOrders po 
DECLARE @n int,@error int
--set @n=1 
set @error=0
  BEGIN TRAN --申明事務
    declare @tmp varchar(50),@userN varchar(50) --臨時變數,用來儲存遊標值
    declare y_curr cursor for --申明遊標 為orderNum,userName
    select orderNum,userName from FOrders where Orderid<50
    open y_curr
    fetch next from y_curr into @tmp,@userN
    while @@fetch_status = 0
      BEGIN
        select isnull(sum(MoneyTotal),0),orderNum from #t where 
[email protected]
        -- set @[email protected]+1         set @[email protected][email protected]@error--記錄每次執行sql後 是否正確 0正確         fetch next from y_curr into @tmp,@userN       END     IF @error=0     BEGIN   commit tran --提交 END ELSE   BEGIN     ROLLBACK TRAN --回滾   END close y_curr deallocate y_curr DROP TABLE #t