I have some columns with no primary key and want to add a primary key column.
NAME Age
-------------
Peter 45
Bob 25
John 56
Peter 45
Some collegues suggest to add a PK with a sequences and triggers: Add a auto increment primary key to existing table in oracle
This is nice, but my customers use a Database User with no rights to add sequences or triggers. I want to prevent to contact dozens of DBA administrators to alter user rights or to run my scripts.
This is my suggestion to add a PK with only an update statement: (I need help in Step 2)
Step 1: Create the ID column (I have DB rights for this)
ALTER TABLE PERSON ADD ID NUMBER(10,0);
Step 2: Question: Can I initialize the ID column with unique values based on the order of the rows or something else? How?
UPDATE PERSON SET ID = something-unique
Step 3: Add the primary key contraint afterwords: (I DB have rights for this)
ALTER TABLE PERSON ADD CONSTRAINT PK_ID PRIMARY KEY(ID);
Step 4: Afterwords: the primary key is managed and added by my application.
This will be the result:
ID(PK) NAME Age
---------------------
1 Peter 45
2 Bob 25
3 John 56
4 Peter 45
Thanks folks!
Because a table can have only one primary key, you cannot add a primary key to a table that already has a primary key defined. To change the primary key of a table, delete the existing key using a DROP clause in an ALTER TABLE statement and add the new primary key.
Yes, there is a way to do the cascading update in Oracle, even within a transaction (which does not hold true for the option of enabling/disabling constraints). However, you'll have to implement it yourself. It can be done via before/after-row-update triggers.
Update person set id = rownum;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With