Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rename a primary key in Oracle such that it can be reused

On Oracle, I create a table like this:

CREATE TABLE "Mig1"(
  "Id" INTEGER  NOT NULL
  , CONSTRAINT "PK_Mig1" PRIMARY KEY 
(
   "Id"  ) 
) 

Then, I rename the PK:

ALTER TABLE "Mig1" RENAME CONSTRAINT "PK_Mig1" TO "PK_XXX"

Then, I rename the table:

ALTER TABLE "Mig1" RENAME TO "XXX"

Then, I try to create another table that uses the name of the previously renamed table:

CREATE TABLE "Mig1"(
  "Id" INTEGER  NOT NULL
  , CONSTRAINT "PK_Mig1" PRIMARY KEY 
(
   "Id"  ) 
) 

At this point I get: An error occurred: ORA-00955: name is already used by an existing object. And this is because somehow the primary key of the first table is still around in some way although it was renamed. If I try to create the second table like this:

CREATE TABLE "Mig1"(
  "Id" INTEGER  NOT NULL
  , CONSTRAINT "YYY" PRIMARY KEY 
(
   "Id"  ) 
) 

it works. So how do I rename the primary key correctly with all of its associated resources such that its name can be reused?

like image 386
Dejan Avatar asked Jun 06 '11 12:06

Dejan


People also ask

Can I modify primary key in Oracle?

Modify Primary KeyThe only syntax supported by Oracle database is to modify the state of the primary key. For example, to disable the primary key constraint, we can do this: SQL> alter table hr.

Is primary key always unique in Oracle?

a primary key is a unique constraint PLUS not null constraints. all NOT NULL columns should be marked as NOT NULL -- hence, if it is a true primary key -- use it.

Can we rename constraint?

The RENAME CONSTRAINT statement changes the name of a constraint on a column.


1 Answers

There is an index associated with the primary key constraint, and it is probably still called "PK_Mig1". Try this:

ALTER INDEX "PK_Mig1" RENAME TO "PK_XXX";
like image 143
Tony Andrews Avatar answered Nov 24 '22 06:11

Tony Andrews