加入收藏 | 设为首页 | 会员中心 | 我要投稿 新余站长网 (https://www.0790zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长百科 > 正文

oracle – PL / SQL:如何从游标创建类型

发布时间:2021-01-25 20:31:00 所属栏目:站长百科 来源:网络整理
导读:我可以从游标定义类型吗? 目前我必须编写以下内容以便从某些表字段创建记录变量: declare cursor cur is select f_1,f_2,f_3,f_4 from mytable where 1=0; myvar cur%rowtype; -- use the cursor to declare myvarbegin null;end; 我想写这样的东西: decl

我可以从游标定义类型吗?

目前我必须编写以下内容以便从某些表字段创建记录变量:

declare

    cursor cur
    is
        select 
            f_1,f_2,f_3,f_4
        from
            mytable
        where 
            1=0;

    myvar cur%rowtype;              -- use the cursor to declare myvar

begin
    null;
end;

我想写这样的东西:

declare

    cursor cur
    is
        select 
            f_1,f_4
        from
            mytable
        where 
            1=0;

    type mytype is cur%rowtype;     -- declare "mytype" from cursor
    myvar mytype;                   -- use "mytype" to declare "myvar"

begin
    null;
end;

这在这个简单的例子中看起来并不有用,但在实际问题中可能有用.

另一种方法是手动创建记录类型:

declare

    type mytype is record           -- declare "mytype"
    (
        f_1    mytable.f_1%type,f_2    mytable.f_2%type,f_3    mytable.f_3%type,f_4    mytable.f_4%type
    );
    myvar mytype;                   -- use "mytype" to declare "myvar"

begin
    null;
end;

但它对我来说更脏(我必须重复每个字段名称两次,并且表名称多次).

解决方法

Can I define a type from a cursor?

是的,你可以定义你自己的类型,它基于cursor_name%rowtype记录类型(在这种情况下基本上它将是一个同义词),使用subtype关键字,而不是类型1.

这是一个例子:

set serveroutput on;
declare
  cursor c1 is
    select 1 as col1,2 as col2,3 as col3
     from dual;

  subtype mytype is c1%rowtype;
  l_myvar mytype;
begin
  open c1;
  fetch c1 into l_myvar;
  dbms_output.put(to_char(l_myvar.col1) || ' : ');
  dbms_output.put(to_char(l_myvar.col2) || ' : ');
  dbms_output.put_line(to_char(l_myvar.col3));
  close c1;
end;

结果:

anonymous block completed

1 : 2 : 3

(编辑:新余站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读