首页 > 解决方案 > 如何动态地将列名传递给查询?

问题描述

以下是我的问题和所需的解决方案。

查询1:

Select colnames from table1;

Query1 Result:
 col1
 col2
 col3
 col4

查询2:

Select a1.* 
  from table2 a1;

-- should translate to
select a1.col1, a1.col2, a1.col3, a1.col4 from table2 a1;

我的第一个查询将给出列名列表,我需要在第二个查询中将 .* 替换为这些列名。我怎样才能做到这一点?

标签: sqloracleselectplsqldynamic-sql

解决方案


您正在寻找动态 SQL。这个想法是从 SQL 查询的结果中生成查询字符串。然后,您可以使用execute immediate.

在您的用例中,这看起来像:

declare
    p_sql varchar2(100);
begin
    select 
        'select ' 
        || listagg('a1.' || colnames, ', ') within group(order by colnames)
        || ' from table2 a1'
    into p_sql
    from table1;

    dbms_output.put_line('sql: ' || p_sql);  -- debug
    execute immediate p_sql;                 -- execute
end;
/

对于您的示例数据,这会生成

dbms_output:
sql: select a1.col1, a1.col2, a1.col3, a1.col4 from table2 a1

推荐阅读