MSSQL游标基本操作

use LibraryDB
--【1】定义游标
declare cur_student cursor for 
select
Sno,Sname,Sage,Sex,Mobileno 
from Student 
where Sex='男'
--【2】打开游标
open cur_student
--【3】使用游标
declare @sno int,@sname varchar(10),@sage tinyint,@sex char(2),@mobile char(11)
while(1=1)
begin
    fetch next from
cur_student into @sno,@sname,@sage,@sex,@mobile
    if(@@FETCH_STATUS=-1) break
    print cast(@sno as char(7))+@sname+' '+cast(@sage as char(4))+' '+@sex+' '+@mobile
end
--【4】关闭游标
close cur_student
--【5】删除游标
deallocate cur_student
go
--游标类型1:local,global(默认)
--local类型批处理结束后自动注销,global需要关闭、删除处理

declare cur_student cursor local for select sname from student
--游标类型2:forward_only(默认,只能使用fetch next from cur_student),scroll(可支持以下几种)
declare cur_student cursor local scroll for select sname from student
--取第一行:fetch first
--取最后一行:fetch last
--取下一行:fetch next
--取上一行:fetch piror
--取第三行:fetch absolute 3
--取上一行:fetch relative-1
--===============================
--游标状态@@fetch_status为全局变量,返回int类型,基值
-- 0:fetch语句成功
-- -1:fetch语句失败或此行不在结果集中
-- -2:被提取的行不存在

--===========游标使用案例===============
--使用Print打印出没有被借过的书的ID,名称,出版社和作者名称
--【方法一】嵌套

select BookID
from Book
where BookID not in
(
    
select distinct BookID from BorrowBook
)

--【方法二】连接

--【1】定义游标
declare cur_borrowbook cursor local forward_only for
(
select T1.BookID,BookName,PressName,AuthorName
from Book as T1 left outer join BorrowBook as T2 on T1.BookID=T2.BookID
               
inner join Press as T3 on T1.BookPressID=T3.PressID
                
inner join Author as T4 on T1.BookAuthor=T4.AuthorID
where BorrowDate is NULL
)
--【2】打开游标
open cur_borrowbook
--【3】使用游标
declare @bookid int,@bookname varchar(30),@pressname varchar(30),@authorname varchar(20)
print '图书编号             图书名称              出版社名称                作者'
print '====================================================================================='
while(1=1)
begin
    fetch next from
cur_borrowbook into @bookid,@bookname,@pressname,@authorname
    
if(@@FETCH_STATUS=-1) break
    print cast(@bookid as char(7))+' '+cast(@bookname as char(30))+' '+cast(@pressname as char(30))+' '+cast(@authorname as char(10))
end
--【4】关闭游标
close cur_borrowbook
--【5】删除游标
deallocate cur_borrowbook

发布了6 篇原创文章 · 获赞 0 · 访问量 63

猜你喜欢

转载自blog.csdn.net/qiuzhimin0/article/details/104290880