SQL遊標的簡單使用

在此之前,曾看過大神們對遊標的一些看法,即遊標其實就像C語言中的指針一樣,對於很多人來說,使用遊標非常之不好用。在此,我只寫一下兩個使用遊標的簡單例子。

1、使用遊標進行查詢數據庫記錄。這裏是查詢作者表的一些信息:

go
declare @auid char(12),@aulname varchar(20), @age int,@sex varchar(2)
declare auth_cur cursor for
select Aid, authorname, age, sex
from author
open auth_cur
fetch next from auth_cur into @auid,@aulname,@age, @sex
while (@@fetch_status=0)
  begin
    if @age<18 
    begin
		print '作者編號: '+@auid
		print '作者姓名: '+@aulname
		print '所年齡: '+(cast(@age as nvarchar))
		print '性別:'+@sex
    end
    fetch next from auth_cur into @auid,@aulname,@age, @sex
  end
close auth_cur
deallocate auth_cur

2、使用遊標更新數據、刪除數據

go
declare @aid int,@authorname nvarchar(50),@age int,@sex nvarchar(2)
declare curs_delete_update_author cursor 
for select aid,authorname,age,sex from author
open curs_delete_update_author
fetch curs_delete_update_author into @aid,@authorname ,@age,@sex
while @@FETCH_STATUS=0 
begin
  if @aid>20
  begin
    update author
    set age=60
    where AId=@aid --current of curs_delete_update_author;
  end
  if @aid>20 and @aid<30
  begin
    delete from author
    where AId=@aid 
  end
  fetch next from  curs_delete_update_author into @aid,@authorname ,@age,@sex
end
close curs_delete_update_author
deallocate curs_delete_update_author



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章