问题
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!
回答1:
Update person set id = rownum;
回答2:
THis idea is very childish, but should work fine if your table doesnot have large amount of rows.
For step 2, run a for loop like:
declare
i pls_integer :=1;
begin
for rec in (select name,age, rowid from table_name)
loop
update table_name set id = i
where
table_name.name=rec.name
and table_name.age=rec.age
and table_name.rowid = rec.rowid;
i:=i+1;
end loop;
end;
来源:https://stackoverflow.com/questions/19807314/oracle-sql-add-primary-key-to-table