Oracle PL/SQL:从具有许多公共列名的两个不同游标初始化单个记录类型的最佳方法?

问题描述 投票:0回答:1

我有两个不同的游标,具有非常不同的 SQL,其结果集有许多共同的属性(假设有 50 个)。例如:

   CURSOR cursor_a(...) IS
     SELECT a1, a2, ..., a10, c1, c2, ...., c50 
       FROM ...

   CURSOR cursor_b(...) IS
     SELECT b1, b2, ..., b20, c1, c2, ...., c50 

我想要一个可以在 PL/SQL 过程定义中使用的“通用”记录类型,这样我就可以轻松地传入cursor_a%ROWTYPE 或cursor_b%ROWTYPE 的通用列:

   TYPE common_type IS RECORD (
      c1 NUMBER,
      c2 VARCHAR2(20),
      ...
      c50 VARCHAR2(1000 CHAR)
   )

   PROCEDURE handle_common_data_proc(common_p IN common_type) IS ... 
   BEGIN
      ... reference fields as common_p.c1, etc. ...
   END;   

我试图避免像这样的详尽初始化,因为如果开发人员向游标添加新的公共字段,很容易出错。另外,当你有很多属性时,它会很难看。

   FOR a_rec IN cursor_a LOOP:
      common_v.c1 := a_rec.c1;
      common_v.c2 := a_rec.c2;
      ...
      common_v.c50 := a_rec.c50;       
      handle_common_data_proc(common_v);
   END LOOP;

   FOR b_rec IN cursor_b LOOP:
      common_v.c1 := b_rec.c1;
      common_v.c2 := b_rec.c2;
      ...
      common_v.c50 := b_rec.c50;       
      handle_common_data_proc(common_v);
   END LOOP;

用面向对象的术语来说,我真的只想让两个光标行都是公共基类的“子类”。或者,或者我希望 Oracle 自动从兼容的记录类型初始化记录类型。

最优雅的方法是什么?谢谢!

oracle plsql polymorphism database-cursor oracle-type
1个回答
0
投票

执行此操作的一个选项是使两个游标返回带有

的列
  • 同名
    • 例如,两个光标中的第一列必须是
      ID
      ,第二列必须是
      NAME
      ,等等
  • 相同的数据类型
    • 例如,both游标中第一列的数据类型必须为
      number(10)
      ,第二列的数据类型必须为
      varchar2(15)
      ,等等

只有这样你才能声明一个继承游标数据类型的single游标变量。哪个光标? 任何,因为它们的描述是相同的 - 上一步确保了这一点。

这是一个例子:


SQL> set serveroutput on
SQL> declare
  2    -- both cursors share the same column NAMES *and* DATATYPES
  3    -- for all columns involved
  4    cursor cur_d is
  5      select cast(deptno as number(10))   as id,
  6             cast(dname  as varchar2(15)) as name,
  7             cast(loc    as varchar2(20)) as col3
  8      from dept;
  9    cursor cur_e is
 10      select cast(empno as number(10))    as id,
 11             cast(ename as varchar2(15))  as name,
 12             cast(job   as varchar2(20))  as col3
 13      from emp;
 14
 15    -- if that's so, declare one cursor variable; it doesn't matter which
 16    -- cursor is the "source" as they are - basically - the same
 17    cur_r cur_d%rowtype;
 18  begin
 19    open cur_d;
 20    fetch cur_d into cur_r;
 21    dbms_output.put_line(cur_r.id ||' - '|| cur_r.name || ' - '|| cur_r.col3);
 22    close cur_d;
 23
 24    open cur_e;
 25    fetch cur_e into cur_r;
 26    dbms_output.put_line(cur_r.id ||' - '|| cur_r.name || ' - '|| cur_r.col3);
 27    close cur_e;
 28  end;
 29  /
10 - ACCOUNTING - NEW YORK
7369 - SMITH - CLERK

PL/SQL procedure successfully completed.

SQL>

现在用新列扩展光标是一个简单的任务 - 只需遵循规则即可。

© www.soinside.com 2019 - 2024. All rights reserved.