嵌套的Oracle / PLSQL for循环用于插入值

时间:2018-08-15 10:10:37

标签: oracle plsql

我收到错误

  

ORA-00984:此处不允许使用列

当我运行此PLSQL脚本时:

BEGIN
    FOR i IN (
        SELECT attribute_id
        FROM odd_attribute
    ) LOOP
        FOR j IN (
            SELECT t1.sourceattribute_id
            FROM odd_sourceattribute t1
            WHERE t1.sourcetable_id IN (
                SELECT t2.sourcetable_id
                FROM odd_sourcetable t2
                WHERE t2.sourcetable_name LIKE 'vr_db_f_%'
            )
        ) LOOP
            EXECUTE IMMEDIATE 'insert into odd_fact_attribute 
                          (attribute_id, sourceattribute_id, statusattribute_name, other_stuff_to_describe_fact) 
                          values 
                          (i.attribute_id, j.sourceattribute_id, NULL, NULL)'
            ;
        END LOOP;
    END LOOP;
END;

列名似乎是正确的,我无法找出错误的原因。感谢所有帮助。谢谢。

1 个答案:

答案 0 :(得分:3)

引发错误是因为您正在引用EXECUTE IMMEDIATE引号中隐式游标的列名,这些引号将被视为静态sql中的表引用。

您可以借助占位符(以:开头)和USING语句来避免这种情况。

EXECUTE IMMEDIATE 
'INSERT INTO odd_fact_attribute (
        attribute_id,
        sourceattribute_id,
        statusattribute_name,
        other_stuff_to_describe_fact
    ) VALUES (
        :attribute_id,
        :sourceattribute_id,
        NULL,
        NULL
    )'
    USING i.attribute_id,j.sourceattribute_id;

重要的是,不需要EXECUTE IMMEDIATE,并且带有嵌套循环的PL / SQL块等效于这样的单个INSERT语句,这将比循环更有效。 / p>

INSERT INTO odd_fact_attribute (
    attribute_id,
    sourceattribute_id,
    statusattribute_name,
    other_stuff_to_describe_fact
)
    SELECT o.attribute_id,
           t1.sourceattribute_id,
           NULL,
           NULL
    FROM odd_sourceattribute t1
    CROSS JOIN odd_attribute o --use appropriate join condn. if this is not the case
    WHERE t1.sourcetable_id IN (
        SELECT t2.sourcetable_id
        FROM odd_sourcetable t2
        WHERE t2.sourcetable_name LIKE 'vr_db_f_%'
    );