Oracle序列+触发器+主键(实现主键自增)
2017-04-18 15:09
1036 查看
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 ONtable_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
);
-- 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 ONtable_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
);
相关文章推荐
- 在Oracle下基于序列和触发器实现主键自增长
- oracle 利用序列和触发器实现主键自增demo
- 通过序列和触发器实现Oracle主键自增长
- Oracle序列和触发器实现表的主键自增
- Oracle - 使用序列+触发器实现主键自增长
- oracle使用序列和触发器实现主键的自动增长
- Oracle序列和触发器实现表的主键自增
- Oracle 实现主键自动增长之序列,触发器
- Oracle序列和触发器实现表的主键自增
- oracle 主键应用序列和触发器实现自动增长
- Oracle使用sequence(序列)+tirgger(触发器)实现auto_increment(主键自增)
- oracle主键自增长_序列及触发器实现
- Oracle用触发器实现插入数据主键自增
- oracle利用触发器实现主键的自动增加
- oracle中使用序列和触发器实现单个字段值自增长
- 在oracle下触发器实现主键自增
- Oracle主键ID设置自动增长(序列+触发器)
- 在oracle下触发器实现主键自增
- 在Oracle下实现主键自增(触发器)
- Oracle使用序列和触发器实现自增ID