PL/SQL游标

游标

在 sql 执行的时候会在内存中开辟一个区域,这个区域叫 context 上下文环境,游标 cursor 就是指向这个内存区域的一个指针。

游标的作用

通过游标来操作 SQL 语句执行的返回结果。

游标的属性

属性名作用
sql%rowcountrowcount 影响的记录数
%found游标中有没有下一条 true/false – rs.next()
%notfound游标中有没有下一条 true/false – rs.hasNext()
%isopen标识当前游标有没有开启执行 true/false

游标的分类

隐式游标 : 由数据库管理系统创建调用执行
显示游标:由程序员创建调用执行,能直接对其进行操作。

游标的使用

1.定义游标
2.开启,调用执行
3.操作游标,获取数据
4.关闭游标
示例:

declare
	--定义游标
	-- Cursor 游标名 is 查询语句
	cursor mycursor is select empno,ename from test_emp ;
		v_id binary_integer;
		v_name varchar2(20);
begin
--开启执行游标
	open mycursor;
		loop
			fetch mycursor into v_id,v_name;
		exit when mycursor%notfound ;
			dbms_output.put_line(v_id);
			dbms_output.put_line(v_name);
		end loop;
	--关闭游标
	close mycursor;
end;

使用游标获取所有的字段

DECLARE
	-- 定义一个游标
	CURSOR mycursor IS SELECT * FROM temp_emp WHERE deptno=20;
	v_emp temp_emp%ROWTYPE; 
BEGIN
	-- 打开游标
	OPEN mycursor ;
		-- 循环读取
		LOOP 
		-- FETCH mycursor INTO v_no,v_name,v_job;
		FETCH mycursor INTO v_emp ;
		-- 如果读到最后一条 -- 游标指针已经到最后
			IF mycursor%NOTFOUND THEN
			EXIT;
			END IF;
			dbms_output.put_line(v_emp.empno || v_emp.ename );
		END LOOP;
	CLOSE mycursor;
END;

使用传参游标
注意点:重名或查询条件和参数名不一致都会出错

declare
	--定义游标时传参
		cursor mycursor(v_empno number) is select empno,ename from test_emp where empno=v_empno ;
		v_id binary_integer;
		v_name varchar2(20);
begin
	--开启执行游标 调用时传实参
	open mycursor(7788);
		loop
		--操作游标,获得数据
		fetch mycursor into v_id,v_name;
			exit when mycursor%notfound ;
				dbms_output.put_line(v_id);
				dbms_output.put_line(v_name);
		end loop;
		--关闭游标
	close mycursor;
end;

定义游标变量

declare
	--定义游标类型 return 返回一个记录
	type cursor_type is ref cursor return test_emp%rowtype;
	--定义变量,类型是游标类型
	mycursor cursor_type;
	--定义变量为记录类型
	myrecord test_emp%rowtype;
begin
	--开启执行游标并赋值
	open mycursor for select * from test_emp;
		loop
			fetch mycursor into myrecord;
			exit when mycursor%notfound;
				dbms_output.put_line(myrecord.empno||myrecord.ename);
		end loop;
	close mycursor ;
end;
----- 分割线 ------
declare
	v_input char(1) := upper('&c');
	type cursor_type is ref cursor ;
	type record_type is record (id binary_integer,name varchar2(10));
	myrecord record_type;
	mycursor cursor_type;
begin
	if 'D'=v_input then
		open mycursor for select deptno,dname from dept;
	elsif 'E'= v_input then
		open mycursor for select empno,ename from emp;
	else
		dbms_output.put_line('no data');
	end if;
	loop
		fetch mycursor into myrecord;
		exit when mycursor%notfound;
		dbms_output.put_line(myrecord.id||myrecord.name);
	end loop;
end;

更多相关知识请关注我哟,也可以戳我的主页,嘻嘻,谢谢!

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值