Dynamic column name to record type variable

会有一股神秘感。 提交于 2020-01-06 08:33:18

问题


 DECLARE
 TYPE t IS RECORD (
 col_name   VARCHAR2 (100)
 );

  t_row   t;
  cname   VARCHAR (100) := 'col_name';
BEGIN
  t_row.col_name             := 'col';
 DBMS_OUTPUT.put_line ('out');

  IF t_row.cname IS NULL THEN
    DBMS_OUTPUT.put_line ('in');
  END IF;
 END;

Error at line 1
ORA-06550: line 12, column 12:
PLS-00302: component 'CNAME' must be declared
ORA-06550: line 12, column 3:
PL/SQL: Statement ignored

How can I assign dynamic column name to type variable of record?


回答1:


You can do that with dynamic sql:
To make the example simpler I'll make your type t a schema object (but basically you don't have to - you can put it in the dynamic part as well)

create or replace type t is object(col_name varchar2(100));
/

Then you can look at this script:

declare
  t_row t;
  cname varchar2(100) := 'col_name';
begin

  t_row := new t('col');

  execute immediate 'declare t_in t := :0; begin if t_in.' || cname ||
                    ' is null then dbms_output.put_line(''in''); end if; end;'
    using t_row;
end;

Though, I must say, that this is a strange requirement ...




回答2:


The error is because record t doesn't have a field cname, but col_name:

type t is record (
  col_name varchar2(100)
);

One have to know record fields during compile time.

Could tell us what is the real problem you're going to solve ?



来源:https://stackoverflow.com/questions/9511391/dynamic-column-name-to-record-type-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!