游标语法
declare c1 cursor for
select title from titles
--定义一个游标c1,确定游标对应的列是titles表的title列,游标可以对应多个列
declare @bname varchar(50)
--声明变量
open c1
--初始化,开始使用游标
fetch next from c1
into @bname
--初始化游标c1到i=0,即起始位置,把游标对应列的值放入变量中,用作输出
while @@FETCH_STATUS=0
--判断游标状态,是否到最后一行
begin
print 'the name of the book is '+@bname
--对每行做数据做相应操作
fetch next from c1
into @bname
--完成操作后,游标后移,再次把游标对应行的该列值放入变量,重复直到游标到最后一列
end
close c1 --关闭游标
deallocate c1 --销毁游标
practice
first:多个变量,聚合函数输出,返回多个字符串
declare b cursor for
select title_id from titleauthor
declare @titleid1 varchar(50),@sum1 int,@sum2 int,@sum3 int
open b
fetch next from b
into @titleid1
while @@FETCH_STATUS=0
begin
set @sum1=(select count(*) from sales where title_id=@titleid1 and ord_date between '1992-1-1' and '1992-12-30')
set @sum2=(select count(*) from sales where title_id=@titleid1 and ord_date between '1993-1-1' and '1993-12-30')
set @sum3=(select count(*) from sales where title_id=@titleid1 and ord_date between '1994-1-1' and '1994-12-30')
print @titleid1+' '+cast(@sum1 as varchar(10))+' '+cast(@sum2 as varchar(10))+' '+cast(@sum3 as varchar(10))
fetch next from b
into @titleid1
end
close b
deallocate b
second:多个变量,返回表
declare c cursor for
select title_id from titleauthor
declare @titleid2 varchar(50),@asum1 int,@asum2 int,@asum3 int
create table #temptable(
titleid varchar(100),
count92 int,
count93 int,
count94 int)
open c
fetch next from c
into @titleid2
while @@FETCH_STATUS=0
begin
set @asum1=(select count(*) from sales where title_id=@titleid2 and ord_date between '1992-1-1' and '1992-12-30')
set @asum2=(select count(*) from sales where title_id=@titleid2 and ord_date between '1993-1-1' and '1993-12-30')
set @asum3=(select count(*) from sales where title_id=@titleid2 and ord_date between '1994-1-1' and '1994-12-30')
insert into #temptable values(@titleid2,@asum1,@asum2,@asum3)
fetch next from c into @titleid2
end
close c
deallocate c
select * from #temptable
drop table #temptable