如何在表中添加唯一标识符列?

时间:2019-03-06 16:15:39

标签: sql oracle

我有一个没有唯一标识符的表。我想在表中添加唯一列,如何实现呢?

我的桌子看起来像这样:

name age     gender      marital_status
SAM          M           Single
BOB          M           Married
JEN          F           Single
BOB          M           Married

我希望我的桌子像这样:

id      name age     gender      marital_status
1        SAM          M           Single
2        BOB          M           Married
3        JEN          F           Single
4        BOB          M           Married

我要具有唯一标识符的原因是,因为某些记录是彼此重复的,所以我想删除重复项。

2 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

alter table t add id int;

create sequence t_seq;

update t set id = t_seq.nextval;

alter table t modify id primary key;

不幸的是,我认为Oracle不允许您将列放在列列表的开头。它总是添加到最后。

答案 1 :(得分:0)

演示表:

create table people (name, gender, marital_status)
as
select 'SAM', 'M', 'Single' from dual union all
select 'BOB', 'M', 'Married' from dual union all
select 'JEN', 'F', 'Single' from dual union all
select 'BOB', 'M', 'Married' from dual;

添加标识列(需要Oracle 12.1或更高版本):

alter table people add id integer generated always as identity;

如果需要,请重新排列字典顺序,以便在描述表时首先显示新列(也需要Oracle 12.1):

begin
    for r in (
        select column_name from user_tab_columns c
        where  c.table_name = 'PEOPLE'
        and    c.column_name <> 'ID'
        order by c.column_id
    )
    loop
        execute immediate 'alter table people modify ' || r.column_name || ' invisible';
        execute immediate 'alter table people modify ' || r.column_name || ' visible';
    end loop;
end;
/