首页 文章

Oracle SQL - 将主键添加到表

提问于
浏览
10

我有一些没有主键的列和 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 triggersAdd a auto increment primary key to existing table in oracle

这很好,但 my customers use a Database User with no rights to add sequences or triggers . 我想阻止与数十名DBA管理员联系以更改用户权限或运行我的脚本 .

This is my suggestion to add a PK with only an update statement: (I need help in Step 2)

第1步:创建ID列(我有此权限)

ALTER TABLE PERSON ADD ID NUMBER(10,0);

第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

第3步:在词语后添加主键约束:(我有权使用此权限)

ALTER TABLE PERSON ADD CONSTRAINT PK_ID PRIMARY KEY(ID);

第4步:后记:主键由我的应用程序管理和添加 .

这将是结果:

ID(PK)  NAME    Age
---------------------
1       Peter   45
2       Bob     25
3       John    56
4       Peter   45

谢谢大家!

2 回答

  • 1
    Update person set id = rownum;
    
  • 24

    这个想法很幼稚,但如果你的表没有大量的行,应该可以正常工作 .

    对于第2步,运行for循环,如:

    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;
    

相关问题