--游标(fetch在循环外面)
declare cursor cu_pro is
select id,pname,price from product;
pid product.id%type;
pname product.pname%type;
price product.price%type;
begin
open cu_pro;
fetch cu_pro into pid,pname,price;
while cu_pro%found loop
dbms_output.put_line('编号:'||pid||',名称:'||pname||',价格:'||price);
fetch cu_pro into pid,pname,price;
end loop;
close cu_pro;
end;
--静态游标(fetch在循环里面,用loop包裹)
declare cursor cu_product is
select id,pname,price from product;
pid product.id%type;
pname product.pname%type;
price product.price%type;
begin
open cu_product;
loop
fetch cu_product into pid,pname,price;
exit when cu_product%notfound;--exit必须存在于exit中
dbms_output.put_line('编号:'||pid||',名称:'||pname||',价格:'||price);
end loop;
close cu_product;
end;
--静态游标(使用行变量)
declare cursor cu_product is
select * from product;
pro product%rowtype;
begin
open cu_product;
loop
fetch cu_product into pro;
exit when cu_product%notfound;
dbms_output.put_line('编号:'||pro.id||',名称:'||pro.pname||',价格:'||pro.price);
end loop;
close cu_product;
end;
--动态游标(强类型)
begin
declare
type pro_cu is ref cursor
return product%rowtype;--返回类型(强制类型)
e_count number;
product_cu pro_cu;--游标变量
products product%rowtype;--行变量
begin
select count(*) into e_count from product where pname='ronaldo';
case
when e_count>0 then
open product_cu for select * from product where pname='ronaldo'; --游标打开指定的sql查询
when e_count>2 then
open product_cu for select * from product;
else
open product_cu for select * from product;
end case;
loop
fetch product_cu into products;
exit when product_cu%notfound;
dbms_output.put_line('编号:'||products.id||',名称:'||products.pname||',价格:'||products.price);
end loop;
end;
end;
--动态游标(弱类型):弱类型不需要指定返回的类型
begin
declare
type pro_cus is ref cursor;
e_count number;
emps emp%rowtype;
products product%rowtype;
pro_cu pro_cus;
begin
select count(*) into e_count from product where pname='ronaldo';
case
when e_count>0 then
open pro_cu for select * from product where pname='ronaldo';
loop
fetch pro_cu into products;
exit when pro_cu%notfound;
dbms_output.put_line('编号:'||products.id||',名称:'||products.pname||',价格:'||products.price);
end loop;
else
open pro_cu for select * from emp;
loop
fetch pro_cu into emps;
exit when pro_cu%notfound;
dbms_output.put_line('姓名:'||emps.ename||'工作:'||emps.job);
end loop;
end case;
end;
end;
分享到:
相关推荐
下面,我们将深入探讨Oracle游标的使用示例及其相关的知识点。 首先,游标的基本概念是它提供了一种方式来跟踪并控制SQL查询的结果集。在Oracle中,游标有四种状态:未打开、已打开、正在提取和已关闭。以下是一个...
### Oracle游标使用详解 #### 一、Oracle游标简介 在Oracle数据库中,游标是一种重要的机制,用于处理查询结果集。它允许用户通过PL/SQL编程语言逐行访问和处理查询返回的数据记录。游标可以是显式定义的(即在...
总之,Oracle游标提供了处理查询结果的强大工具,使开发者能够灵活地在PL/SQL中操作数据。无论是隐式还是显式游标,都极大地增强了对数据库的交互能力,使得程序能根据查询结果进行适当的操作。理解并熟练运用游标是...
Oracle游标是数据库编程中非常重要的一个概念,主要用于处理SQL查询的结果集。游标允许我们按行处理数据,逐条读取结果集,而不仅仅是一次性获取所有数据。在Oracle数据库中,游标对于复杂的事务处理、动态SQL以及...
Oracle 游标使用方法及语法大全 Oracle 游标是 PL/SQL 程序中的一种重要组件,用于处理查询结果集。游标可以分为隐式游标和显式游标两种,隐式游标由 PL/SQL 管理,隐式游标打开时查询开始,查询结束时隐式游标自动...
### Oracle游标使用及实例详解 #### 一、Oracle游标概述 在Oracle数据库中,游标(Cursor)是一种用于处理SQL查询结果集的方式。它允许用户逐行地读取和处理查询结果,这对于需要对每一行数据进行特定操作的情况非常...