數據源
pubs 示例數據庫
目標
利用遊標用於生成作者出版情況報表,形式如下:
-------- Authors report --------
----- Books by Author: AuthorName1
BookName1
BookName2
----- Books by Author: AuthorName2
BookName1
BookName2
實現
-- 使用遊標
begin
print('-------- Authors report --------')
-- 聲明存儲作家信息的變量
declare @au_name varchar(20), @au_lname varchar(20), @au_fname varchar(20),
@au_id varchar(20)
-- 聲明作家遊標
declare c_author_name cursor
for select au_lname, au_fname from authors
declare c_author_id cursor
for select au_id from authors
-- 打開作家遊標
open c_author_name
open c_author_id
-- 重置全局變量 @@fetch_status
fetch next from c_author_id into @au_id
fetch next from c_author_name into @au_lname, @au_fname
-- 作家層循環
while @@fetch_status = 0
begin
-- 拼接作家名稱
set @au_name = @au_lname + ' ' + @au_fname
print '----- Books by Author:' + @au_name
-- 書號
declare @book_id varchar(20)
-- 書號遊標
declare c_book_id cursor
for select title_id from titleauthor where au_id = @au_id
open c_book_id
fetch next from c_book_id into @book_id
-- 書號層循環
while @@fetch_status = 0
begin
-- 書名
declare @book_name varchar(20)
-- 書名遊標
declare book_name cursor
for select title from titles where title_id = @book_id
open book_name
fetch from book_name into @book_name
print @book_name
close book_name
deallocate book_name
fetch next from c_book_id into @book_id
end
close c_book_id
deallocate c_book_id
fetch next from c_author_id into @au_id
fetch next from c_author_name into @au_lname, @au_fname
end
-- 關閉作家遊標
close c_author_id
close c_author_name
-- 釋放作家遊標
deallocate c_author_id
deallocate c_author_name
end
-- 不使用遊標
select au_lname, au_fname, title
from authors, titleauthor, titles
where authors.au_id = titleauthor.au_id and titles.title_id = titleauthor.title_id