oracle自增主键的添加[sequence](转)

  • Post author:
  • Post category:其他


1:一个sequence可以被多个表共享。

2:被多个表共享的sequence生成的数字序列始终连续,不会重新开始。

3:如果不再使用的sequence请删除。

SELECT * FROM DAYSBFJ.DAYS_CARD_UPDATE3 order by id asc

–alter table DAYSBFJ.DAYS_CARD_UPDATE3 add source_Flag varchar2(2);

–create sequence DAYS_CARD_UPDATE2_SEQ_ID minvalue 1 maxvalue 999999999 start with 1;

–Update DAYSBFJ.DAYS_CARD_UPDATE2 set id = DAYS_CARD_UPDATE2_SEQ_ID.nextval;

–update DAYSBFJ.DAYS_CARD_UPDATE3 set SOURCE_FLAG = ‘2’

一个例子:

新建一个缺少主键的表

create table test1(name1 varchar2(40),city varchar2(40));

–插入数据

insert into test1 values(‘name1′,’nanjing’);

insert into test1 values(‘name1′,’nanjing’);

insert into test1 values(‘name2′,’nanjing1’);

insert into test1 values(‘name3′,’nanjing2’);

insert into test1 values(‘name4′,’nanjing3’);

insert into test1 values(‘name5′,’nanjing4’);

insert into test1 values(‘name6′,’nanjing5’);

insert into test1 values(‘name7′,’nanjing6’);

insert into test1 values(‘name8′,’nanjing7’);

insert into test1 values(‘name9′,’nanjing8’);

insert into test1 values(‘name10′,’nanjing9’);

insert into test1 values(‘name10′,’nanjing9’);

insert into test1 values(‘name12′,’nanjing11’);

insert into test1 values(‘name13′,’nanjing12’);

insert into test1 values(‘name14′,’nanjing13’);

commit;

–增加主键ID

alter table TEST1 add id number(10);

–设置sequence使ID自增

create sequence SEQ_ID

minvalue 1

maxvalue 999999999

start with 1;

–将id的值设置为sequence

Update test1 set id=seq_id.nextval;

commit;

–设置id为主键

alter table TEST1

add constraint PK_TEST1 primary key (ID);

select ID,Name1,CITY from TEST1;