oracle自增字段設置
以前在使用mysql 和SQL server時,他們都有自增字段設置的關鍵字,在創建表時一併創建。現在使用oracle發現沒有自增字段這樣的功能,可以通過觸發器trigger和序列sequence來實現:
先建一個測試表:
create table scott.TableName
(
id number(6) not null,
name varchar2(30) not null primary key
)
第一步:創建SEQUENCE
create sequence SeqName
increment by 1
start with 1
minvalue 1
maxvalue 9999999999999
nocache order;
第二步:創建一個基於該表的before insert 觸發器,在觸發器中使用剛創建的SEQUENCE
create or replace trigger TriggerName
before insert on scott.TableName
for each row
begin
select SeqName.nextval into:new.id from sys.dual ;
end;
第三步:在TableName表中測試
insert into scott.TableName (name) values ('wang');
先建一個測試表:
create table scott.TableName
(
id number(6) not null,
name varchar2(30) not null primary key
)
第一步:創建SEQUENCE
create sequence SeqName
increment by 1
start with 1
minvalue 1
maxvalue 9999999999999
nocache order;
第二步:創建一個基於該表的before insert 觸發器,在觸發器中使用剛創建的SEQUENCE
create or replace trigger TriggerName
before insert on scott.TableName
for each row
begin
select SeqName.nextval into:new.id from sys.dual ;
end;
第三步:在TableName表中測試
insert into scott.TableName (name) values ('wang');
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.