views:

8858

answers:

7

Am I correct in understanding that CREATE OR REPLACE basically means "if the object exists, drop it, then create it either way?"

If so, what am I doing wrong? This works:

CREATE TABLE foo (id NUMBER,
title VARCHAR2(4000) DEFAULT 'Default Title')

And this doesn't (ORA-00922: missing or invalid option):

CREATE OR REPLACE TABLE foo (id NUMBER,
title VARCHAR2(4000) DEFAULT 'Default Title')

Am I doing something stupid? I don't seem to be able to find much documentation about this syntax.

+7  A: 

This works on functions, procedures, packages, types, synonyms, trigger and views.

Update:

After updating the post for the third time, I'll reformulate this:

This does not work on tables :)

And yes, there is documentation on this syntax, and there are no REPLACE option for CREATE TABLE.

Quassnoi
Sigh, I swear I read that it did somewhere. Oh well. :)
Jason Baker
It also doesn't work for materialized views
skaffman
+2  A: 

There is no create or replace table in Oracle.

You must:

DROP TABLE foo;
CREATE TABLE foo (....);
RC
+2  A: 

Does not work with Tables, only functions etc.

Here is a site with some examples.

northpole
+2  A: 

CREATE OR REPLACE can only be used on functions, procedures, types, views, or packages - it will not work on tables.

Andy Mikula
A: 

If this is for MS SQL.. The following code will always run no matter what if the table exist already or not.

if object_id('mytablename') is not null //is there data in the table
Begin
     drop table mytablename
End

Create table mytablename (...
JuniorFlip
Sorry, but this is Oracle. :-)
Jason Baker
is the comment "//is there data in the table" accurate?
Jeffrey Kemp
sorry a little better, the object_id check to see if the table exists in the db. it should say //has the table been created already in the db
JuniorFlip
+3  A: 

One of the nice things about the syntax is that you can be sure that a CREATE OR REPLACE will never cause you to lose data (the most you will lose is code, which hopefully you'll have stored in source control somewhere).

The equivalent syntax for tables is ALTER, which means you have to explicitly enumerate the exact changes that are required.

EDIT: By the way, if you need to do a DROP + CREATE in a script, and you don't care for the spurious "object does not exist" errors (when the DROP doesn't find the table), you can do this:

BEGIN
  DROP TABLE owner.mytable;
EXCEPTION
  WHEN OTHERS THEN
    IF sqlcode != -0942 THEN RAISE; END IF;
END;
/
Jeffrey Kemp
A: 

Following script should do the trick on Oracle:

BEGIN
  EXECUTE IMMEDIATE 'drop TABLE tablename';
EXCEPTION
  WHEN OTHERS THEN
    IF sqlcode != -0942 THEN RAISE; 
    END IF;
END;
Kavan