Oleksandr Gavenko's blog
2017-03-05 23:50 Create table if not exists in Oracle

We need to reset our Flyway history due to major DB refactoring. All changes would be squashed into a single that creates a base schema to be able to recreate database from scratch.

But we don't want conflicts with existing tables in production.

MySQL database has syntax to prevent error on create table if table already exists:

create table if not exist "TBL" (...);

Unfortunately Oracle database doesn't have such syntax. It can be mimicked with PL/SQL code block and exception handling. Because PL/SQL code doesn't allow DDL code dynamic queries are used:

declare
begin
  execute immediate 'create table "TBL" ("ID" number not null)';
  exception when others then null;
end;
/

More safer implementation checks for error code:

ORA-00955: name is already used by an existing object

which same for create table, and create index, and create sequence, etc and report error otherwise. Final solution looks like:

declare
begin
  execute immediate '
    create table "TBL" ("ID" number not null)';
  exception when others then
    if SQLCODE = -955 then null; else raise; end if;
end;
/
sql, oracle

Feeds

all / emacs / java

Tags

adb(1), admin(1), android(1), anki(1), ansible(2), aop(1), blog(2), bytecode(1), c(1), css(2), cygwin(2), driver(1), emacs(3), fs(1), git(3), google(1), gradle(1), hardware(1), hg(2), html(1), interview(13), java(4), js(3), lang(2), lighttpd(1), markdown(1), mobile(1), naming(1), oracle(1), print(1), problem(5), python(1), quiz(6), rst(2), security(3), spring(2), sql(2), srs(1), style(1), tls(2), txt(1), unit(1), utils(1), vcs(3), web(2), win(2), windows(1)

Archive