Dreamer
Dreamer

Reputation: 7549

how to upgrade an existing column to a foreign key using sql query?

I have a oracle table A which contains a column A.a which used to store an attribute of the table. It is a big table with data. Now the semantic requirement of attribute A.a needs to develop into another table called B, B has an id column, and a column B.a which stores the same set of data as A.a (both columns are unique).

So now A.a should upgrade to a foreign key of the table B, then A.a should store B.id instead of VARCHAR2 and also the more tough part is I need to use A.a to find B.id via B.a and rewrite A.a with B.id because table A has existing data.

And I have to achieve this via SQL query.

So how to get this work? Apologize if I didn't make myself clear. Please feel free to leave any idea. Thanks in advance.

Upvotes: 1

Views: 5408

Answers (1)

Jeffrey Kemp
Jeffrey Kemp

Reputation: 60312

If you have the following schema:

tableA { a, x }

You want to transform it to the following schema:

tableB { id, a }
tableA { id, x } where id has a FK constraint to tableB (id)

You can do it with something like the following sequence of commands:

-- sequence to generate the tableB's surrogate key
CREATE SEQUENCE tableB_id_seq;

-- generate tableB
CREATE TABLE tableB AS
  SELECT tableB_id_seq.NEXTVAL AS id, a
  FROM (SELECT DISTINCT a
        FROM   tableA);

ALTER TABLE tableB MODIFY (id PRIMARY KEY);

-- add the FK column on tableA
ALTER TABLE tableA ADD (id NUMBER);

-- populate it
UPDATE tableA SET id = 
  (SELECT tableB.id
   FROM tableB
   WHERE tableB.a = tableA.a);

-- make it a FK
ALTER TABLE tableA ADD CONSTRAINT afk
  FOREIGN KEY (id) REFERENCES tableB (id);

-- drop the old column
ALTER TABLE tableA DROP COLUMN a;

Upvotes: 4

Related Questions