Oracle資料庫中建立自增主鍵的執行個體教程_oracle

來源:互聯網
上載者:User

在設計資料庫表的時候發現Oracle沒有自增主鍵的設定,Google瞭解到Oracle本身並不支援自增主鍵,需要通過序列(Sequence)和觸發器(Trigger)實現。
建立表Student

Create Table Student(  id number(12) primary key, --通過序列和觸發器實現id的自增  name varchar2(20) ,  age number(3) ,  sex number(1) ) 

建立序列Sequence

Create Sequence SEQ_STUDENT minvalue 1 maxvalue 99999999999999999999 start with 1   --從1開始 increment by 1 --增量為1 cache 0 order; 

建立觸發器Trigger

Create or Replace Trigger STUDENT_AUTOINCREMENT Before Insert on Student For Each Row When (NEW.ID IS NULL) Begin Select SEQ_STUDENT.NEXTVAL INTO :NEW.ID FROM DUAL; End; 

注意點:

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;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.