我有3张桌子。我想为每个下表生成ID,并且每个表都应该是唯一的。 表1 ID - 主要 ID 1 - > 2 - > 3 表2 ID - 主要 ID 4 - >五 表3 ID - 主要 ID 6 - > 7 - > 8 每当对上表进行新的输入时,它应该在表中生成唯一值 下次我要将2条记录插入表1时应该是 表1 ID - 主要 ID 9 - > 10。
我们是否可以在Oracle
中创建触发器来完成此任务答案 0 :(得分:0)
在每张桌子上使用触发器并创建Sequence
CREATE SEQUENCE seq
START WITH 1
INCREMENT BY 1
NOCACHE
NOCYCLE;
然后在插入触发器上执行以下操作:
select seq.nextval
into :new.id
from dual;
之前有人问过。看here
CREATE OR REPLACE TRIGGER my_trigger
BEFORE INSERT
ON qname
FOR EACH ROW
-- Optionally restrict this trigger to fire only when really needed
WHEN (new.qname_id is null)
DECLARE
v_id qname.qname_id%TYPE;
BEGIN
-- Select a new value from the sequence into a local variable. As David
-- commented, this step is optional. You can directly select into :new.qname_id
SELECT qname_id_seq.nextval INTO v_id FROM DUAL;
-- :new references the record that you are about to insert into qname. Hence,
-- you can overwrite the value of :new.qname_id (qname.qname_id) with the value
-- obtained from your sequence, before inserting
:new.qname_id := v_id;
END my_trigger;