Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can not have CREATE TABLE inside if else

Tags:

sql

oracle

When I run this query

DECLARE
      num NUMBER;
BEGIN

    SELECT COUNT(*) INTO num FROM user_all_tables WHERE TABLE_NAME=upper('DatabaseScriptLog')
    ;

    IF num < 1 THEN

      CREATE TABLE DatabaseScriptLog 
      (ScriptIdentifier VARCHAR(100) NOT NULL,
       ScriptType VARCHAR(50), 
       StartDate TIMESTAMP, 
       EndDate TIMESTAMP, 
       PRIMARY KEY (ScriptIdentifier)
       );

    END IF;

END;

When execute the above, I got the following:

PLS-00103: Encountered the symbol "CREATE" when expecting one of the following:

begin case declare exit for goto if loop mod null pragma raise return select update while with << close current delete fetch lock insert open rollback
savepoint set sql execute commit forall merge pipe 06550. 00000 - "line %s, column %s:\n%s" *Cause: Usually a PL/SQL compilation error.

like image 773
rsd Avatar asked Dec 27 '22 19:12

rsd


1 Answers

You cannot run DDL statements like that. You need to use dynamic SQL (EXECUTE IMMEDIATE).

IF num < 1 THEN

  EXECUTE IMMEDIATE 'CREATE TABLE DatabaseScriptLog (ScriptIdentifier VARCHAR(100) NOT NULL, ScriptType VARCHAR(50), StartDate TIMESTAMP, EndDate TIMESTAMP, PRIMARY KEY (ScriptIdentifier))'

END IF;
like image 74
Thilo Avatar answered Jan 15 '23 18:01

Thilo