Select into Table from Table2 where column in (Subquer)

Posted

技术标签:

【中文标题】Select into Table from Table2 where column in (Subquer)【英文标题】: 【发布时间】:2014-09-18 13:03:16 【问题描述】:

我在plsql中写了:

w_table    USER_TAB_COLS.TABLE_NAME%TYPE  :='T481INPUTRIGADOC' ;

cursor selecttable is

select cols.*
FROM USER_TAB_COLS cols 
JOIN USER_TABLES tabs ON cols.TABLE_NAME = tabs.TABLE_NAME
WHERE 1=1
AND cols.COLUMN_NAME LIKE '%IDANAGPROPRIETARIO%' --Dovrei prenedere ogni i-esimo elemento della lista
ORDER BY cols.TABLE_NAME, cols.COLUMN_ID;


BEGIN
    tmpVar := 0;

    w_esitoElaborazione:='OK';
    w_descrizioneErrore:='';

    FOR REC IN selecttable LOOP
        w_cnt_record := w_cnt_record+1;
        w_table := REC.TABLE_NAME;
        w_col := REC.COLUMN_NAME;

        select w_col into a from w_table;

    end loop

但问题出在选择查询中,因为输出中有写

[错误] ORA-00942 (76: 30): PL/SQL: ORA-00942: 表或视图不存在

【问题讨论】:

您连接的用户是否有权访问这些系统视图? 问题不在于视图,而在于w_table 是一个VARCHAR,而不是一个表,所以你不能像这样从中选择。 但问题是我必须从中选择 w_col 的表的名称包含在表 'USER_TAB_COLS'(cursor selecttable) 的字段 'COLUMN_NAME' 中。如何查询? 【参考方案1】:

在形成整个 quire 字符串之后,您已经使用 EXECUTE IMMEDIATE 进行了 SQL 调用 动态

 FOR REC IN selecttable LOOP
        w_cnt_record := w_cnt_record+1;
        w_table := REC.TABLE_NAME;
        w_col := REC.COLUMN_NAME;

        EXECUTE IMMEDIATE 'select '||w_col||' from '||w_table INTO a;

end loop

【讨论】:

我同意 OP 想要立即执行 EXECUTE IMMEDIATE 并且您已经解决了当前的问题。对于绝大多数情况,这将引发错误。对于非单一记录场景,OP 将需要“BULK COLLECT INTO”或类似方法。

以上是关于Select into Table from Table2 where column in (Subquer)的主要内容,如果未能解决你的问题,请参考以下文章

Select into Table from Table2 where column in (Subquery)

“With”命令比使用临时表慢 Select * into #table1 from

select into from 和 insert into select 的用法和区别

oracle数据库表复制insert into select from跟create table as select * from 两种表复制语句区别

Select into Table from Table2 where column in (Subquer)

Select into 与 Insert into … select … from