[Oracle]高效的PL/SQL程序设计(六)--%ROWTYPE的使用

来源:互联网 发布:热血英豪mac下载 编辑:程序博客网 时间:2024/05/09 20:29

本系列文章导航

[Oracle]高效的PL/SQL程序设计(一)--伪列ROWNUM使用技巧

[Oracle]高效的PL/SQL程序设计(二)--标量子查询

[Oracle]高效的PL/SQL程序设计(三)--Package的优点

[Oracle]高效的PL/SQL程序设计(四)--批量处理

[Oracle]高效的PL/SQL程序设计(五)--调用存储过程返回结果集

[Oracle]高效的PL/SQL程序设计(六)--%ROWTYPE的使用

 在PL/SQL程序中, 我们会遇到需要先从一个结果集中取出若干记录, 然后对每一条记录进行处理的情况, 最理想的做法是在一条SQL语句中完成, 但有时候因为需求的关系所以不一定能实现, 所以我们通常会定义几个变量, 然后对结果集做循环, 赋值给变量. 最典型的就是select XX into XX。我们也可以用定义一个记录%rowtype的方法, 减少不必要的代码量, 还能避免由于表中字段的变更造成的错误。示例如下:

创建测试表:

create table t1 as select * from user_tables

创建PACKAGE HEAD:

create or replace package Type_demo is

 
procedure process1(p_record in t1%rowtype);
 
procedure process_data(p_inputs in varchar2);

end Type_demo;

创建PACKAGE BODY:

create or replace package body Type_demo is

procedure process1(p_record in t1%rowtype)
as 
begin      
       dbms_output.put_line(p_record.tablespace_name);
end;

procedure process_data(p_inputs in varchar2)
as
begin
       
for x in(select * from t1 where table_name like p_inputs)
       loop
           process1(x);
       
end loop;
end;

end Type_demo;

上面的例子得到的是整个表的记录类型, 如果想要得到某几个列的记录类型, 可以按照如下做法:

create or replace package Type_demo is

 
cursor template_cursor
    
is select table_name,tablespace_name from t1;

 
--type rc is ref cursor;

 
procedure process2(p_record in template_cursor%rowtype);
 
procedure process_data(p_cname in varchar2,p_inputs in varchar2);
end Type_demo;
create or replace package body Type_demo is

procedure process2(p_record in template_cursor%rowtype)
as 
begin  
       dbms_output.put_line(p_record.tablespace_name);
end;

procedure process_data(p_cname in varchar2,p_inputs in varchar2)
as
  
--l_cursor rc;
  l_cursor sys_refcursor;
  l_rec template_cursor
%rowtype;
begin
     
open l_cursor
     
for
     
'select table_name,tablespace_name from t1 where '|| p_cname ||' like :x' using p_inputs;
     loop
         
fetch l_cursor into l_rec;
         
exit when l_cursor%notfound;
         process2(l_rec);
     
end loop;
end;

end Type_demo;

注:还有一个获得列的数据类型%TYPE

l_tablename t1.tablename%type;
   select XX into l_tablename from t1 where...

 

博文来源:http://blog.csdn.net/huanghui22/archive/2007/05/24/1624358.aspx

原创粉丝点击