当前位置: 首页 > 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

http://www.dtcms.com/a/166413.html

相关文章:

  • 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:文件操作
  • 婴幼儿急救实训室优化空间布局科学路径5.7
  • 苍穹外卖11
  • 2025东三省B题深圳杯B题数学建模挑战赛数模思路代码文章教学
  • Python 错误 — 此环境由外部管理error: externally-manage(如何解决)
  • [第十五章][15.3.2 shellcode注入攻击]ret2shellcode+[NewStarCTF 公开赛赛道]ret2shellcode
  • OLED显示字符串 汉字 图形
  • 腾讯元宝桌面客户端:基于Tauri的开源技术解析
  • 智能驾驶新时代:NVIDIA高级辅助驾驶引领未来出行安全
  • 机器学习_KNN算法
  • 边缘计算:数字世界的”末梢神经系统”解析-优雅草卓伊凡