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

数据库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.xdnf.cn/news/3331.html

相关文章:

  • 安全指南 | MCP安全检查清单:AI工具生态系统的隐形守护者
  • 深入浅出循环神经网络(RNN):原理、应用与实战
  • Tomcat DOS漏洞复现(CVE-2025-31650)
  • 数据库规范
  • 国产化海光C86架构服务器安装windows实录
  • Transformer架构指南:从原理到实战资源全更新
  • 用Power shell脚本批量发布rdl文件到SQL Server Reporting Service
  • 详细介绍C++中指针解引用
  • 枚举法——C++算法【泪光2929】
  • ShardingSphere5详细笔记
  • Vue2 和 Vue3 的核心区别
  • 腾讯云web服务器配置步骤是什么?web服务器有什么用途?
  • TM1668芯片学习心得二
  • 【SpringBoot】基于mybatisPlus的博客系统
  • 【计算机视觉】目标检测:深度解析MMDetection:OpenMMLab开源目标检测框架实战指南
  • Winform(6.序列化方式)
  • 港口危货储存单位主要安全管理人员考试精选题目
  • [Unity]设置自动打包脚本
  • Copilot 祝你走在AI前沿:2025 年 4 月动态
  • 小程序中的页面跳转
  • TimeDistill:通过跨架构蒸馏的MLP高效长期时间序列预测
  • 有状态服务与无状态服务:差异、特点及应用场景全解
  • leetcode76
  • Vue+tdesign t-input-number 设置长度和显示X号
  • 智能驾驶新时代:NVIDIA高级辅助驾驶引领未来出行安全
  • iOS 性能调优实战:三款工具横向对比实测(含 Instruments、KeyMob、Xlog)
  • C语言与Unix的传奇起源
  • (32)VTK C++开发示例 ---背景纹理
  • pytorch中的变量内存分配
  • WPF之RadioButton控件详解