1. 程式人生 > >Transact-SQL的遊標例項

Transact-SQL的遊標例項

print '------------- Authors report ---------------'
print ''
--定義authors表的遊標
declare author_cursor cursor for
select au_id,au_fname,au_lname
from authors
--宣告變數
declare @au_id varchar(100),@au_fname varchar(100),@au_lname varchar(100)
open author_cursor
fetch next from author_cursor into @au_id,@au_fname,@au_lname
--對authors表項進行迴圈檢查每個作者
while @@FETCH_STATUS=0
begin

--列印格式要求的字串
print ''
print '--------- Books by Author: '
[email protected]
_lname+' '[email protected]_fname declare @title_id varchar(100) --定義titleauthor表的遊標 declare titleauthor_cursor scroll cursor for select title_id from titleauthor where [email protected]_id open titleauthor_cursor fetch next from titleauthor_cursor into @title_id --對當前作者的titleauthor表項進行遍歷 while @@FETCH_STATUS=0 begin declare @title varchar(100),@pubdate varchar(100) --定義titles表的遊標 declare titles_cursor scroll cursor for select title,pubdate from titles where
[email protected]
_id open titles_cursor fetch next from titles_cursor into @title,@pubdate --對相應title_id的title表項進行遍歷,這裡其實可以去除這一層迴圈 while @@FETCH_STATUS=0 begin --列印格式輸出,包括書籍書目和出版時間 print ' '[email protected]+' '[email protected] fetch next from titles_cursor into @title,@pubdate end close titles_cursor deallocate titles_cursor fetch next from titleauthor_cursor into @title_id end close titleauthor_cursor deallocate titleauthor_cursor fetch next from author_cursor into @au_id,@au_fname,@au_lname end close author_cursor deallocate author_cursor