您的位置:首页 > 数据库 > Oracle

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

);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: