Oracle序列+触发器+主键(实现主键自增)

1.SEQUENCE(序列)


-- Create sequence
create sequence table_name_ID_SEQ
minvalue 1
maxvalue 9999999999
start with 1
increment by 1
cache 20;


2.触发器(triggers)


CREATE OR REPLACE TRIGGER " table_name_trigger" BEFORE INSERT OR UPDATE ON table_name
FOR EACH ROW
DECLARE
v_newVal NUMBER(10) := 0;
v_incval NUMBER(10) := 0;
BEGIN
IF INSERTING AND :new.id IS NULL THEN
SELECT table_name_id_SEQ.NEXTVAL INTO v_newVal FROM DUAL;
-- If this is the first time this table have been inserted into (sequence == 1)
IF v_newVal = 1 THEN
--get the max indentity value from the table
SELECT NVL(max(id),0) INTO v_newVal FROM table_name;
v_newVal := v_newVal + 1;
--set the sequence to that value
LOOP
EXIT WHEN v_incval>=v_newVal;
SELECT table_name_id_SEQ.nextval INTO v_incval FROM dual;
END LOOP;
END IF;
--used to emulate LAST_INSERT_ID()
--mysql_utilities.identity := v_newVal;
-- assign the value from the sequence to emulate the identity column
:new.id := v_newVal;
END IF;
END;


3.主键和索引

-- Create/Recreate primary, unique and foreign key constraints
alter table table_name
add primary key (ID)
using index
tablespace QRPAY
pctfree 10
initrans 2
maxtrans 255
storage
(
initial 128K
next 1M
minextents 1
maxextents unlimited
);




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值