当前位置: 首页 > news >正文

数据库12(游标)

游标语法

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

相关文章:

  • 2025年-redis(p1-p10)
  • D365 开发环境证书到期替换处理
  • ant-design 表格多选无法显示,选一个选项全部被选中
  • 牛客:AB4 逆波兰表达式求值
  • 启动Hadoop集群及集群效果
  • ai改写智能助手在线润色,高效产出优质文章!
  • Java 数据类型之间的转换入门
  • OpenCV的grabCut算法分割图像
  • Windows结合WSL之ext4.vhdx不断增大问题
  • Unity URP RenderTexture优化(二):深度图优化
  • PCI总线数据采集卡 32路多功能异步模拟量信号采集卡
  • 【C/C++】线程池_学习笔记
  • 6轴、智能、低功耗惯性测量单元BMI270及其OIS接口
  • CrowdStrike推出新型工具防御恶意AI模型与数据窃取
  • 全局事件总线EventBus的用法
  • 【keil使用】无法打开keil工程,只有空白界面的解决方法
  • 练习001
  • ReentrantReadWriteLock的源码详细剖析
  • 使用 ossutil 上传文件到阿里云 OSS
  • Linux:文件操作
  • 证监会:坚决拥护党中央对王建军进行纪律审查和监察调查的决定
  • 民生访谈|支持外贸企业拓内销,上海正抓紧制定便利措施
  • 病人有头发,照护者不发疯:《黑镜》中的身体缺席与虚伪关怀
  • 昆明破获一起算命破灾诈骗案,民警:大师算不到自己的未来
  • 人社部:我国劳动力市场潜力足,韧性强
  • 超级干细胞有助改善生育治疗