在另一个 table 的 select 子句中使用一个 table 的列值

Using column values from one table within a select clause from another table

我有一个名为 col_mapping 的 Oracle table,其中此 table 中的列具有另一个 [= =34=].

table的示例数据:col_mapping

    ID    DESCR     COL_VALS
------------------------------
    1     LABEL     COL_1
    2     NAME_ADDR COL_2:COL_3
    3     SALARY    COL4

基于上述 table,我现在想遍历 col_mapping 中的每条记录,并将 COL_VALS 作为我的

的一部分
select COL_VALS from other_tab

显然,如果有多个值,如 COL_2:COL_3,需要将“:”替换为“,”

    SELECT COL_1 from other_tab;
    SELECT COL_2,COL_3 from other_tab;
    SELECT COL_4 from other_tab;

您可以使用动态 SQL 基于 col_vals 值生成并执行插入语句,在 col_mappings 行的游标循环内:

begin
  for r in (select replace(col_vals, ':', ',') as cols from col_mapping) loop
    dbms_output.put_line('insert into staging_tab(' || r.cols || ')'
      || ' select ' || r.cols || ' from other_tab');
    execute immediate 'insert into staging_tab(' || r.cols || ')'
      || ' select ' || r.cols || ' from other_tab';
  end loop;
end;
/

游标刚好得到cols_val值,用逗号代替了冒号。生成的插入使用修改后的 cols_val 作为插入列列表和 select 列表 - 因为您说暂存 table 将匹配 other_tab 结构。

dbms_output 行只是为了让您可以看到生成的语句 - 代码不需要 运行,您需要 set serveroutput on 或等效的无论如何都要看到它。启用后,运行使用您的示例映射数据显示该块显示:

PL/SQL procedure successfully completed.

insert into staging_tab(COL_1) select COL_1 from other_tab
insert into staging_tab(COL_2,COL_3) select COL_2,COL_3 from other_tab
insert into staging_tab(COL4) select COL4 from other_tab

您最终得到的是 other_tab 中每一行的数据分布在 staging_tab 中的多行中,其中包含大量空值。希望这就是您的意图。