隐式游标
游标名字:SQL(用于系统自己创建的处理处理update/delete/insert的游标)
游标属性
1.游标名称%found:如果有返回受影响的行数,返回true,否则返回false
2.游标名称%rowcount:返回受影响的行数
3.游标名称%notfound:如果没有返回受影响的行数,返回true,否则返回false
4.游标名称%isopen:游标是否打开,如果打开返回true,否则返回false
隐式游标自动打开或关闭,不需要手动打开或关闭。
隐式游标你看到的永远为false。
示例:
if(SQL%found = true) then
dbms_output.put_line('修改成功,修改了'||SQL%rowcount||'条数据');
end if;
(注:SQL%notfound,SQL%isopen都是如此用法)
显示游标
- 定义:处理select查询结果集的,指向结果集的指针
- 游标属性
1.游标名称%found:如果有返回受影响的行数,返回true,否则返回false
2.游标名称%rowcount:返回受影响的行数
3.游标名称%notfound:如果没有返回受影响的行数,返回true,否则返回false
4.游标名称%isopen:游标是否打开,如果打开返回true,否则返回false
显示游标不会自动打开或关闭,需要手动打开或关闭
- 语法:声明游标并指向查询结果集(打开–提取–关闭)
// 声明游标并指向查询结果集:cursor 游标名字 is select 查询结果集
declare
cursor 游标名字
is
select结果集;
begin
open 游标名字;--打开游标
loop --循环
fetch 游标名字 into 变量1,变量2,...;--提取
end loop; --结束循环
close --关闭
end
for循环遍历游标
for循环遍历游标:简化游标操作(则不需要打开游标,关闭游标,以及提取fetch)
语法:for 变量 in 游标语言
示例:查询所有员工的姓名和薪水
declare
cursor my_car(游标名)
is
select * form emp;
begin
for r in my_car
loop
dbms_output.put_line('姓名'||r.ename||'薪水'||r.sal);
end loop;
end;
使用带参数的游标,提高游标的灵活性
语法
declare
cursor 游标名字 (参数:变量 变量类型)
使用游标更新数据
语法
declare
cursor 游标名字
is
select 查询结果集 for update nowait; -- 标识修改状态
begin
update/insert/delete ... where current of 游标名
end
标识修改状态:for update nowait;
更新数据的条件就是游标的当前号:where current of 游标名字;
REF游标
REF游标:用于处理运行时才能确定的查询结果集
语法
declare
type REF类型名称 is ref cursor; --定义一个REF游标类型
游标名字 REF类型名称; --指定一个游标为REF游标类型
begin
open 游标名字 for select 查询结果集;--打开游标指向结果集
end
动态SQL
动态SQL:execute immediate ‘SQL语句’
1.用于在PL/SQL块中执行DDL语句,因为PL/SQL中不能直接执行DDL语句
例:在PL/SQL块中执行动态SQL语句创建表
begin
execute immediate
'create table my_test(id number)'
end
例:在PL/SQL块中执行动态SQL语句删除表
begin
execute immediate
'drop table my_test';
end
2.用于执行语句时才能确定的SQL语句
a.声明占位符 =:占位符
b.给占位符填值 using 值
declare
ename emp.ename%type
begin
execute immediate
'select emp.ename from emp where emp.ename=:aa' into ename using &aa;
end