在upsert

时间:2016-01-05 18:27:41

标签: oracle plsql oracle11g

我正在编写一个包含MERGE的部署脚本到一个视图中,该视图在许多目标模式之一中可能存在或不存在(schemii?schemata?)。

我正在尝试这个SQL:

DECLARE
BEGIN
    /* MERGE statement that will work if the view is available */
EXCEPTION
    WHEN OTHERS THAN
        DBMS_OUTPUT.put_line('warning: merge target is not available');
END;

当我运行此块时,我得到标准的“PL / SQL:ORA-00942:表或视图不存在”错误。

如何捕获此错误并生成警告线?

3 个答案:

答案 0 :(得分:4)

将有效答案与建议的改进结合起来,它们汇集在一起​​:

SET SERVEROUTPUT ON;
PROMPT ...trying UPSERT;

DECLARE
    eTableNotExists exception;
    pragma exception_init(eTableNotExists, -00942);
BEGIN
    EXECUTE IMMEDIATE '<MERGE statement that will work if the view is available--no trailing ";"!>';

    DBMS_OUTPUT.put_line('insert worked');

EXCEPTION
    WHEN eTableNotExists THEN
        DBMS_OUTPUT.put_line('FYI: doesn''t exist on this schema');
END;
/

COMMIT;

SET SERVEROUTPUT OFF;

(查看SERVEROUTPUT

的结果需要DBMS_OUTPUT.put_line()

答案 1 :(得分:2)

您需要使用动态SQL:

BEGIN
    EXECUTE IMMEDIATE 'MERGE ...';
EXCEPTION
    WHEN OTHERS THEN
        DBMS_OUTPUT.put_line('warning: merge target is not available');
END;

答案 2 :(得分:1)

您可以使用动态SQL将此类错误推迟到运行时并将其捕获

EXECUTE IMMEDIATE '<MERGE>' 

而不是“静态”MERGE