一、游标的相关概念:
定义:
游标它是一个服务器端的存储区,这个区域提供给用户使用,在这个区域里
存储的是用户通过一个查询语句得到的结果集,用户通过控制这个游标区域当中
的指针 来提取游标中的数据,然后来进行操作。
实质:
是用户在远程客户端上对服务器内存区域的操作,由数据库为用户提供这样的
一个指针,使得用户能够去检索服务器内存区的数据。
(1)、 指向上下文区域的句柄或指针
(2)、上下文区域-用于SQL处理的内存区
(3)、上下文区域的内容
- 语句处理的行数
二、游标的类型
a)静态游标
- 隐式游标
- 显式游标
b)Ref游标
三、游标具有的属性
%notfound 询问是否没有结果集
%found 询问是否存在结果集
%rowcount 返回受影响的行数
%isopen 询问游标是否已经打开
四、隐式游标
隐式游标 ---由Oracle数据库自动创建,名称是(SQL) ,主要用途是可以返回一个操作是否成功或失败.
1.有Oracle在内部声明,由系统管理
2.用于处理
-DML语句 --注意只能用于DML语句哦。
-返回单行的查询
3.用于判断一个操作是否成功.
SQL%notfound --返回Boolean值 存在结果集返回 False
SQL%found --返回Boolean值 存在结果集返回 True
SQL%rowcount --用户成功提取数据的行数
SQL%isopen --在隐式游标里一般这个属性是自动打开和关闭的.且任何时候查询都返回False
示例:向表中插入一行数据,询问是否插入成功.
declare
iCount int:=0;
begin
insert into place values(2,'beijing');
DBMS_output.put_line('游标所影响的行数:'||SQL%rowcount);
if SQL%NotFount then
DBMS_output.put_line('NotFount为真);
else
DBMS_output.put_line('NofFount为假');
end if;
if SQL%Fount then
DBMS_output.put_line('Fount为真);
else
DBMS_output.put_line('Fount为假');
end if;
if SQL%isopen then
DBMS_output.put_line('isOpen为真);
else
DBMS_output.put_line('isOpen为假');
end if;
isCount:=SQL%rowcount;
DBMS_output.put_line('影响了'||isCount||'行');
end;
显示游标:
SQL> declare
2 --定义游标类型sp_test_cursor
3 type sp_test_cursor is ref cursor;
4 --定义一个游标变量
5 test_cursor sp_test_cursor;
6 --定义变量
7 v_name mytest.name%type;
8 v_passwd mytest.passwd%type;
9 begin
10 --执行 把cursor和一个select结合
11 open test_cursor for select name,passwd from mytest;
12 loop
13 fetch test_cursor into v_name,v_passwd;
14 --跳出循环的条件即判断当前游标是否为空
15 exit when test_cursor%notfound;
16 dbms_output.put_line('name:'||v_name||' passwd:'||v_passwd);
17 end loop;
18 --关闭游标
19 close test_cursor;
20 end;
21 /
name:123 passwd:123
name:gaodingle!!!! passwd:123
name:gagaga passwd:123
name:125555 passwd:passwd
PL/SQL procedure successfully completed
SQL> declare
2 type sp_cursor is ref cursor;
3 test_cursor sp_cursor;
4 v_id mytest.id%type;
5 v_name mytest.name%type;
6 v_passwd mytest.passwd%type;
7 v_salary mytest.salary%type;
8 begin
9 open test_cursor for select id,name,passwd,salary from mytest;
10 loop
11 fetch test_cursor into v_id,v_name,v_passwd,v_salary;
12 if v_salary=100 then
13 update mytest set salary=v_salary+50 where id=v_id;
14 end if;
15 exit when test_cursor%notfound;
16 end loop;
17 close test_cursor;
18 end;
19 /
PL/SQL procedure successfully completed
SQL> select * from mytest;
ID NAME PASSWD SALARY
----- -------------------- -------------------- --------------------------------------------------------------------------------
1 123 123 150
2 gaodingle!!!! 123 150
3 gagaga 123 150
4 125555 passwd 50
作者:翎野君
如果您喜欢或希望看到更多我的文章,关注我的微信公众号《翎野君》。
转载文章请务必保留出处和署名,否则保留追究法律责任的权利。