T-SQL(一)游标嵌套查询

数据源
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
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值