如何获取oracle APEX中动态列名的数据

How to get the data for the dynamic column name in oracle APEX

我想动态获取列名。

declare
  rColNames varchar2(500);
  rColumns varchar2(4000);
  rC varchar2(4000);

BEGIN
  for i in (
    select  name, amount,days -- (More columns will be there)
    from trans_e 
    where name = 'A'
  )
  loop
    --dynamically selected column names 
    --:P2_COLS -- NAME,AMOUNT,DAYS etc...
    for colNames in
    (
      select regexp_substr(:P2_COLS,'[^,]+',1,level) rCol from dual
      connect by level <= length(regexp_replace(:P2_COLS,'[^,]+')) + 1
    )
    loop
      rColNames :=  LOWER(colNames.rCol);
      select 'i.' || rColNames into rColumns from dual; 
      rC := rC ||  rColumns ; 
    end loop;
    
    
   

  end loop;
END;

所以我需要 i.daysrColumns 中的数据。但是我得到的 rColumns 作为 i.days 而不是 i.days 值 10.

如果我直接给出 i.days,我得到值 10。但是如果我给出 'i.' || rColNames,那么我得到 i.days 作为输出,而不是值 10。

如何从i循环中获取动态数据值?

最简单的方法可能是枚举 case 表达式中的列:

loop
  -- append a comma if this isn't the first column
  rC := case when rC is not null then rC || ',' end ||
    case lower(colNames.rCol)
      when 'name' then i.name
      when 'amount' then to_char(i.amount)
      when 'days' then to_char(i.days)
    end;          
end loop;

如果您希望从外部游标返回多行,那么您需要在每行之前清除 rC

declare
  rC varchar2(4000);
begin
  for i in (
    select  name, amount,days -- (More columns will be there)
    from trans_e 
    where name = 'A'
  )
  loop
    -- clear result from previous row
    rC := null;

    --dynamically selected column names 
    --:P2_COLS -- NAME,AMOUNT,DAYS etc...
    for colNames in
    (
      select regexp_substr(:P2_COLS,'[^,]+',1,level) rCol from dual
      connect by level <= length(regexp_replace(:P2_COLS,'[^,]+')) + 1
    )
    loop
      -- append a comma if this isn't the first column
      rC := case when rC is not null then rC || ',' end ||
        case lower(colNames.rCol)
          when 'name' then i.name
          when 'amount' then to_char(i.amount)
          when 'days' then to_char(i.days)
        end;          
    end loop;
  end loop;
end;
/