使用游标中的记录作为表名返回无效的列标识符

时间:2019-05-30 13:33:04

标签: oracle plsql

我有一个表名称的游标,想遍历所有表名称,然后从每个表中选择最新的日期行,以备后用。我尝试使用:

DECLARE

    theDate DATE;

    CURSOR CUR_ALL_TABS IS
        SELECT DISTINCT OWNER, OBJECT_NAME 
        FROM DBA_OBJECTS
        WHERE OBJECT_TYPE = 'TABLE'
        AND OWNER = 'OWNERNAME';

BEGIN
    FOR REC_TAB IN CUR_ALL_TABS 
    LOOP
        EXECUTE IMMEDIATE 'SELECT MAX(dateEntered) FROM ' || REC_TAB.OBJECT_NAME || ''
        INTO theDate;
        DBMS_OUTPUT.PUT_LINE(theDate);
    END LOOP;
END;

但是这返回:

Error report -
ORA-00904: "dateEntered": invalid identifier
ORA-06512: at line 16
00904. 00000 -  "%s: invalid identifier"

当我在单个桌子上尝试时:

DECLARE

    tableName VARCHAR(50);
    theDate DATE;

BEGIN

    SELECT DISTINCT OBJECT_NAME 
    INTO NAMEOF
    FROM DBA_OBJECTS
    WHERE OBJECT_TYPE = 'TABLE'
    AND OWNER = 'OWNERNAME'
    AND OBJECT_NAME = 'ME';
    DBMS_OUTPUT.PUT_LINE(tableName);
    EXECUTE IMMEDIATE 'SELECT MAX(TOC) FROM ' || tableName|| ''
    INTO theDate;
    DBMS_OUTPUT.PUT_LINE(theDate);
END;

我得到了预期的输出。

为什么我的列在游标上尝试此过程时将其引发为无效标识符?我基本上是在做同样的事情,除了它是循环的。

1 个答案:

答案 0 :(得分:0)

您可以这样编写代码块:

DECLARE
    THEDATE   DATE;
    CURSOR CUR_ALL_TABS IS
    SELECT DISTINCT
        DT.OWNER,
        DT.TABLE_NAME
    FROM
        DBA_TABLES DT
    WHERE
        DT.OWNER = 'OWNERNAME'
        AND EXISTS (
            SELECT
                1
            FROM
                DBA_TAB_COLS DTC
            WHERE
                DTC.COLUMN_NAME = 'DATEENTERED'
                AND DTC.TABLE_NAME = DT.TABLE_NAME
        );

BEGIN
    FOR REC_TAB IN CUR_ALL_TABS LOOP
        EXECUTE IMMEDIATE 'SELECT MAX(dateEntered) FROM '
                          || REC_TAB.TABLE_NAME
                          || ''
        INTO THEDATE;
        DBMS_OUTPUT.PUT_LINE(THEDATE);
    END LOOP;
END;

谢谢