Jimenemex
Jimenemex

Reputation: 3166

Creating a table if it doesn't exist already

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.

Upvotes: 0

Views: 1104

Answers (1)

wolφi
wolφi

Reputation: 8361

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;
/

Upvotes: 5

Related Questions