Creating a table if it doesn't exist already

牧云@^-^@ 提交于 2021-02-04 21:39:02

问题


I'm trying to create a table if it doesn't exist already. I'm currently checking to see if it exists in DBA_TABLES first and if that query returns nothing then insert. Is there a way to just check in the same statement so I don't have to break it up into separate queries?

This is what I have currently.

BEGIN
    SELECT COUNT(*)
    INTO lvnTableExists
    FROM DBA_TABLES
    WHERE Table_Name = 'SOME_TABLE';

    IF lvnTableExists = 0 THEN
        EXECUTE IMMEDIATE 'CREATE TABLE SOME_TABLE AS (SELECT * FR0M OTHER_TABLE)';
    END IF;
END;

This is something that I'm going for.

DECLARE
    sql VARCHAR2(100000);
BEGIN
    sql := 'CREATE TABLE SOME_TABLE ' ||
            'AS (SELECT * FROM OTHER_TABLE) ' ||
            'WHERE NOT EXISTS (SELECT NULL ' ||
            'FROM DBA_OBJECTS d WHERE d.Object_Name = 'SOME_TABLE' AND ' ||
            'd.Owner = 'SOME_TABLE')';
    EXECUTE IMMEDIATE sql;
END;

The problem is that, you can't put a WHERE NOT EXISTS in a CREATE TABLE AS statement.


回答1:


Yes, that's really a shame that Oracle doesn't have that functionality. I'm sure it will come some day. Until then, if you want to write a PL/SQL wrapper, why not do it like that:

DEClARE
     table_exists_already exception; 
     pragma exception_init(table_exists_already, -955 ); 
BEGIN
  EXECUTE IMMEDIATE 'CREATE TABLE SOMETABLE...';
EXCEPTION WHEN table_exists_already THEN
  DBMS_OUTPUT.PUT_LINE('Table sometable already exists');
END;
/


来源:https://stackoverflow.com/questions/50593254/creating-a-table-if-it-doesnt-exist-already

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!