SQL SERVER迴圈遍曆(普通迴圈和遊標迴圈)

來源:互聯網
上載者:User

標籤:rollback   修改   查看   from   date   死迴圈   學生   into   ror   

 

1、首先需要一個測試表資料Student

2、普通迴圈

1)迴圈5次來修改學生表資訊

--迴圈遍曆修改記錄--
declare @i int   
set @i=0
while @i<5
begin
    update Student set demo = @i+5 where [email protected]
    set @[email protected] +1 
end
--查看結果--
select * from Student

2)執行後的查詢結果

3、遊標迴圈(沒有事務)

1)根據學生表實際資料迴圈修改資訊
---遊標迴圈遍曆--
begin
    declare @a int,@error int    
    declare @temp varchar(50)
    set @a=1
    set @error=0
    --申明遊標為Uid
    declare order_cursor cursor 
    for (select [Uid] from Student)
    --開啟遊標--
    open order_cursor
    --開始迴圈遊標變數--
    fetch next from order_cursor into @temp
    while @@FETCH_STATUS = 0    --返回被 FETCH語句執行的最後遊標的狀態--
        begin            
            update Student set [email protected],[email protected] where [email protected]
            set @[email protected]+1
            set @error= @error + @@ERROR   --記錄每次運行sql後是否正確,0正確
            fetch next from order_cursor into @temp   --轉到下一個遊標,沒有會死迴圈
        end    
    close order_cursor  --關閉遊標
    deallocate order_cursor   --釋放遊標
end
go
--查看結果--
select * from Student

2)執行後的查詢結果

4、遊標迴圈(事務)

1)根據實際迴圈學生表資訊

---遊標迴圈遍曆--
begin
    declare @a int,@error int    
    declare @temp varchar(50)
    set @a=1
    set @error=0
    begin tran  --申明事務
    --申明遊標為Uid
    declare order_cursor cursor 
    for (select [Uid] from Student)
    --開啟遊標--
    open order_cursor
    --開始迴圈遊標變數--
    fetch next from order_cursor into @temp
    while @@FETCH_STATUS = 0    --返回被 FETCH語句執行的最後遊標的狀態--
        begin            
            update Student set [email protected],[email protected] where [email protected]
            set @[email protected]+1
            set @error= @error + @@ERROR   --記錄每次運行sql後是否正確,0正確
            fetch next from order_cursor into @temp   --轉到下一個遊標
        end    
    if @error=0
    begin
        commit tran   --提交事務
    end
    else
    begin
        rollback tran --復原事務
    end
    close order_cursor  --關閉遊標
    deallocate order_cursor   --釋放遊標
end
go
--查看結果--
select * from Student

2)執行後的查詢結果:

 

SQL SERVER迴圈遍曆(普通迴圈和遊標迴圈)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.