oracle利用觸發器為表生成自增長的主鍵

2021-06-16 17:31:38 字數 2783 閱讀 6467

--建表t_account

create table t_account(

accountid number(8) not null,

accountname varchar(100) not null

)tablespace portalone;

alter table t_account add constraint pk_account primary key(accountid) using index tablespace portaloneindx;

--建序列

create sequence s_account

minvalue 1

maxvalue 99999999

start with 1

increment by 1

cache 20;

--建觸發器

create or replace trigger trigger_t_account

before insert on t_account

for each row when(new.accountid is null)

declare

begin

--從序列中獲取新的序號並賦給新行的id欄位

select s_account.nextval into :new.accountid from dual;

--獲取系統的guid/uuid生成主鍵

--select sys.guid() into :new.accountid from dual;

--獲取系統時間作為表的某個字段值

--select to_char(sysdate, "yyyy-mm")into :new.year_month from dual;

end trigger_t_account;   

--建表t_order

drop table t_order;

create table t_order(

orderid number(8) not null,

accountid number(8) not null,

ordername varchar(100) not null

)tablespace portalone;

alter table t_order add constraint pk_order primary key(orderid) using index tablespace portaloneindx;

alter table t_order add constraint fk_order foreign key(accountid) references t_account(accountid);

--建立序列

create sequence s_order

minvalue 1

maxvalue 99999999

start with 1

increment by 1

cache 20;

--建觸發器

create or replace trigger trigger_t_order

before insert on t_order

for each row when (new.orderid is null)

declare

begin

select s_order.nextval into :new.orderid from dual;

select s_order.currval into :new.accountid from dual;

end trigger_t_order;

--建表t_orderitem

drop table t_orderitem;

create table t_orderitem(

orderitemid number(8) not null,

orderid number(8) not null,

orderitemname varchar(100) not null

)tablespace portalone;

alter table t_orderitem add constraint pk_orderitem primary key(orderitemid) using index tablespace portaloneindx;

alter table t_orderitem add constraint fk_orderitem foreign key(orderid) references t_order(orderid);

--建序列

create sequence s_orderitem

minvalue 1

maxvalue 99999999

start with 1

increment by 1

cache 20;

--建觸發器

create or replace trigger trigger_t_orderitem

before insert on t_orderitem

for each row when (new.orderitemid is null)

declare

begin

select s_orderitem.nextval into :new.orderitemid from dual;

select s_orderitem.currval into :new.orderid from dual;

end trigger_t_orderitem;

分享到:

利用觸發器生成編號

原貼 http munity.csdn.expert topic 4294 4294910.xml?temp 3575403 有一表 id,product id,product name 其中id是自動編號,當向這錶新增資料時候,product id自動新增資料,格式是 wpbh max id 1,...

Oracle生成多表觸發器sql

將所有hy開頭的表都生成乙個更新觸發器的指令碼 是為了連續建立多個觸發器而不報錯 select create or replace trigger table name before update on table name referencing new as new old as old for...

ORACLE觸發器 行級觸發器

行級觸發器 本章介紹行級觸發器機制。大部分例子以insert出發器給出,行級觸發器可從insert update delete語句觸發。1 介紹 觸發器是儲存在資料庫已編譯的儲存過程,使用的語言是pl sql,用編寫儲存過程一樣的方式編寫和編譯觸發器。下面在sql plus會話中建立和示例乙個簡單的...