Transact-SQL的游标实例

本文通过SQL游标的使用示例,展示了如何从authors表中获取作者信息,并进一步查询与其关联的书籍及其出版日期。该过程涉及到了游标的声明、打开、读取及关闭等操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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: '+@au_lname+' '+@au_fname
declare @title_id varchar(100)
--定义titleauthor表的游标
declare titleauthor_cursor scroll cursor for
select title_id
from titleauthor
where au_id=@au_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 title_id=@title_id
open titles_cursor
fetch next from titles_cursor into @title,@pubdate
--对相应title_id的title表项进行遍历,这里其实可以去除这一层循环
while @@FETCH_STATUS=0
begin
--打印格式输出,包括书籍书目和出版时间
print '      '+@title+'  '+@pubdate
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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值