SQL SERVER循環遍歷(普通循環和遊標循環)

 

一、首先須要一個測試表數據Studentsql

二、普通循環測試

1)循環5次來修改學生表信息fetch

--循環遍歷修改記錄--
declare @i int   
set @i=0
while @i<5
begin
    update Student set demo = @i+5 where Uid=@i
    set @i=@i +1 
end
--查看結果--
select * from Studentblog

2)執行後的查詢結果事務

三、遊標循環(沒有事務)it

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 Age=15+@a,demo=@a where Uid=@temp
            set @a=@a+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)執行後的查詢結果date

四、遊標循環(事務)select

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 Age=20+@a,demo=@a where Uid=@temp
            set @a=@a+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)執行後的查詢結果:

相關文章
相關標籤/搜索