Oracle Create Table if it does not exist

前端 未结 4 1027
渐次进展
渐次进展 2020-12-11 03:36

Can anyone point me to the right syntax to use in order to create a table only if it does not currently exist in the database?

I\'m currently programming a Java GUI

相关标签:
4条回答
  • 2020-12-11 03:50
    try
    {
        // insert query for insert new record in your table 
    }
    catch(Exception Ex)
    {
        //if it throw exception then catch it
    
         int s=Ex.getErrorCode(); // check it for 903 error
    
         //903 is table not existing error in oracle11g
    
     // then create your new table here otherwise if table present then record get stored in database
    }
    
    0 讨论(0)
  • 2020-12-11 03:56

    @Archie I would like to answer your question. @Piyas De Sorry for stealing your code :).

    Just a little update of @Piyas De answer.

    BEGIN
        BEGIN
            EXECUTE IMMEDIATE '<<Your table creation Statement>>';
        EXCEPTION
            WHEN OTHERS THEN
                IF SQLCODE == -955 THEN
                    RAISE;
                END IF;
        END;
    END;
    
    0 讨论(0)
  • 2020-12-11 04:00

    Normally, it doesn't make a lot of sense to check whether a table exists or not because objects shouldn't be created at runtime and the application should know what objects were created at install time. If this is part of the installation, you should know what objects exist at any point in the process so you shouldn't need to check whether a table already exists.

    If you really need to, however,

    • You can attempt to create the table and catch the `ORA-00955: name is already used by an existing object" exception.
    • You can query USER_TABLES (or ALL_TABLES or DBA_TABLES depending on whether you are creating objects owned by other users and your privileges in the database) to check to see whether the table already exists.
    • You can try to drop the table before creating it and catch the `ORA-00942: table or view does not exist" exception if it doesn't.
    0 讨论(0)
  • 2020-12-11 04:07

    You can do this with the Following Procedure -

    BEGIN
        BEGIN
             EXECUTE IMMEDIATE 'DROP TABLE <<Your Table Name>>';
        EXCEPTION
             WHEN OTHERS THEN
                    IF SQLCODE != -942 THEN
                         RAISE;
                    END IF;
        END;
    
        EXECUTE IMMEDIATE '<<Your table creation Statement>>';
    
    END;
    

    Hope this may help you.

    0 讨论(0)
提交回复
热议问题