【问题标题】:Dynamically look up column names for a table while in an sql query在 sql 查询中动态查找表的列名
【发布时间】:2010-09-17 09:12:33
【问题描述】:

我正在编写 SQL(用于 Oracle),例如:

INSERT INTO Schema1.tableA SELECT * FROM Schema2.tableA;

其中 Schema1.tableA 和 Schema2.tableA 具有相同的列。但是,这似乎是不安全的,因为在 SELECT 中返回的列的顺序是未定义的。我应该做的是:

插入到 Schema1.tableA (col1, col2, ... colN) 从 Schema2.tableA 中选择 (col1, col2, ... colN);

我正在使用一些脚本为很多表执行此操作,所以我想做的是编写如下内容:

插入到 Schema1.tableA (foo(Schema1.tableA)) 从 Schema2.tableA 中选择(foo(Schema1.tableA));

其中 foo 是一个漂亮的魔法,它从表一中提取列名并将它们打包成适当的语法。想法?

【问题讨论】:

    标签: sql oracle select insert


    【解决方案1】:

    这个 PL/SQL 应该这样做:

    declare
        l_cols long;
        l_sql  long;
    begin
        for r in (select column_name from all_tab_columns
                  where  table_name = 'TABLEA'
                  and    owner = 'SCHEMA1'
                 )
        loop
           l_cols := l_cols || ',' || r.column_name;
        end loop;
    
        -- Remove leading comma
        l_cols := substr(l_cols, 2);
    
        l_sql := 'insert into schema1.tableA (' || l_cols || ') select ' 
                 || l_cols || ' from schema2.tableA';
    
        execute immediate l_sql;
    
    end;
    /
    

    【讨论】:

      【解决方案2】:

      您可能需要使用USER_TAB_COLUMNS 动态构造插入语句并使用EXECUTE IMMEDIATE 执行它们。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多