mysql 、sql server 游标 cursor

游标 声明的位置

游标必须在声明处理程序之前 被声明,并且变量和条件还必须在声明游标或处理程序之前被声明

游标的使用步骤

  1. 声明游标
  2. 打开游标
  3. 使用游标
  4. 关闭游标 (sql server 关闭游标和释放游标)

sql server 游标

复制代码
declare my_cursor cursor for   select   字段1 [, 字段2,。。。字段n ] from  表名 或视图    [ where ]
open my_cursor 
fetch next my_sursor   into    变量1  --  此处变量要在声明游标之前 定义
while @@FETCH_STATUS=0   ---  一个等号  
begin
		sql  语句执行操作
		fetch next my_sursor   into    变量1  --  游标向下移动 一行
end
close   my_cursor
deallcate my_cursor


----案例   

create  PROCEDURE [dbo].[pro_zen]		
	
AS
BEGIN
	declare  @cnt int = 0
	declare  @sco int = 0
	declare  @total int = 0
	---  定义游标
	declare my_cursor  cursor for  select score from Table_1  order by score DESC
	--   打开游标
	open my_cursor
	--   使用游标
	fetch next from my_cursor into @sco 
   while @@FETCH_STATUS=0
	begin
		set @total=@total+@sco
		set @cnt=@cnt+1
		if @total >500 
			break	
        fetch next from my_cursor into @sco 

	end
	print @cnt 
	print @total
	--  关闭游标 
	close my_cursor
	---  释放游标
	deallocate my_cursor
END


mysql 游标


1、声明游标

在Mysql中,使用Declare关键字来声明游标

declare cursor_name cursor for select_statement; ----mysql 、sqlserver

declare cursor_name cursor is select_statement; ----Oracle

上面的 select_statement 代表的是select语句,返回一个用于创建游标的结果集

2、打开游标

open cursor_name ;

定义好游标之后,如果想要使用游标,必须先打开游标,打开游标的时候,select语句的查询结果就会送到游标工作区,为后面游标的逐条读取结果集中的记录做准备

3、使用游标,从游标中获得数据

Fetch cursor_name into var_name [,...var_namen] ;

使用 cursor_name 这个游标来读取当前行,并且将数据保存到var_name这个变量中(这个变量要在声明游标之前定义),游标指针指到下一行 。 如果游标读取的数据行有多个列名,则在into 关键字后面赋值给多个变量名即可。
注意

var_name 必须在声明游标之前定义。

游标的查询结果(select_statement)中的字段, 必须 必须 必须 跟into 后面 的变量 数量保持一致。

Fetch cursor_name into var_name1,var_name2 ; ### 多个变量之间用逗号隔开

4、关闭游标

close cursor_name ;

游标的优缺点

优点

游标是 sql 中重要功能,为了追条读取 结果集中的数据,提供了完美的解决方案。跟在应用层面实现相同的功能相比。

游标可以在存储过程 中使用,效率高,程序也更加简洁。
缺点

在使用游标的过程中,会对数据进行 加锁 。这样在业务并发量大的时候,不但会影响业务之间的效率,还会 消耗系统资源,造成内存不足,这是因为游标是在内存中进行处理的。

建议: 养成用完游标之后,记着close。 这样可以释放资源,提高效率。

相关推荐
x***13391 分钟前
【MyBatisPlus】MyBatisPlus介绍与使用
android·前端·后端
4***14901 小时前
MySQL调试技巧与工具
数据库·mysql
n***54381 小时前
【MySQL】MySQL内置函数--日期函数字符串函数数学函数其他相关函数
android·mysql·adb
z***75152 小时前
【Springboot3+vue3】从零到一搭建Springboot3+vue3前后端分离项目之后端环境搭建
android·前端·后端
程序员陆业聪2 小时前
Android模拟器检测全面指南:从基础到高级策略
android
linchare2 小时前
linux debian上只装mysql的客户端步骤
linux·mysql·debian
w***4243 小时前
【MySQL】复合查询
数据库·mysql
q***01774 小时前
【MySQL】表的基本操作
数据库·mysql·oracle
2501_916008894 小时前
iOS 性能测试的深度实战方法 构建从底层指标到真实场景回放的多工具测试体系
android·ios·小程序·https·uni-app·iphone·webview
w***95494 小时前
SQL美化器:sql-beautify安装与配置完全指南
android·前端·后端