Question

I'd like to check weather a table exists before creating one, in an Oracle database. Though, the following statement is not working throwing error ORA-06550 on line 7 (CREATE).

  DECLARE cnt NUMBER;
  BEGIN
    SELECT COUNT(*) INTO cnt FROM ALL_TABLES WHERE lower(table_name) = lower('TestTable');

    IF( cnt = 0 )
    THEN
      CREATE TABLE TestTable
      (
        TestFlag NUMBER(1) NOT NULL
      );
    END IF;
  END;

Can anyone help me out with this one?

Thanks in advance!

Was it helpful?

Solution

creating tables on the fly in Oracle is a big no-no, so if this is real code you're running then, stop. use temp tables instead. but the reason for failure is that DDL has to be run in SQL, not PL/SQL.

 DECLARE cnt NUMBER;
  BEGIN
    SELECT COUNT(*) INTO cnt FROM ALL_TABLES WHERE lower(table_name) = lower('TestTable');

    IF( cnt = 0 )
    THEN
      execute immediate 'CREATE TABLE TestTable (testFlag NUMBER(1) NOT NULL)';
    END IF;
  END;

OTHER TIPS

Personally, I do not see any reason why would you want to create a table that way, but here is another approach to create a table if it doesn't exist:

 SQL> declare
  2     table_exists exception;
  3     pragma exception_init(table_exists, -955);
  4   begin
  5     execute immediate 'create table TestTable(TestFlag number(1) not null)';
  6     dbms_output.put_line('table created');
  7   exception
  8     when table_exists
  9     then dbms_output.put_line('table exists');
 10   end;
 11  /

table created

SQL> declare
  2    table_exists exception;
  3    pragma exception_init(table_exists, -955);
  4  begin
  5    execute immediate 'create table TestTable(TestFlag number(1) not null)';
  6    dbms_output.put_line('table created');
  7  exception
  8    when table_exists
  9    then dbms_output.put_line('table exists');
 10  end;
 11  /

table exists

PL/SQL procedure successfully completed
DECLARE cnt NUMBER;
  BEGIN
    SELECT COUNT(*) INTO cnt FROM ALL_TABLES WHERE lower(table_name) 
                                                            = lower('TestTable');

    IF( cnt = 0 )
    THEN
      EXECUTE IMMEDIATE 'CREATE TABLE TestTable ( TestFlag NUMBER(1) NOT NULL )';
    END IF;
  END;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top