我需要从表中获取max indentity值并将序列设置为该值。
为此,我试图在此触发器中读取表中的最大缩进值(触发当前触发器)并将序列设置为该值 但是当我去阅读桌子时,我得到了变异的错误。我正在使用Oracle 11g。
所以我的问题是有没有办法在这个触发器中将序列值设置为表的max indentity值?请指教。
这是我的触发器;
create or replace
TRIGGER StringTextTrg BEFORE INSERT ON StringText
FOR EACH ROW
DECLARE
v_newVal NUMBER(12) := 0;
v_incval NUMBER(12) := 0;
BEGIN
IF INSERTING AND :new.STxtID IS NULL THEN
SELECT StringText_STxtID_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(STxtID),0) INTO v_newVal FROM StringText;
v_newVal := v_newVal + 1;
--set the sequence to that value
LOOP
EXIT WHEN v_incval>=v_newVal;
SELECT StringText_STxtID_SEQ.nextval INTO v_incval FROM dual;
END LOOP;
END IF;
-- assign the value from the sequence to emulate the identity column
:new.STxtID := v_newVal;
END IF;
END;
答案 0 :(得分:0)
以下是我的回答,使用哪个是我强烈反对的:
CREATE OR REPLACE TRIGGER StringTextTrg
BEFORE INSERT
ON StringText
FOR EACH ROW
DECLARE
v_newVal NUMBER (12) := 0;
v_incval NUMBER (12) := 0;
BEGIN
IF INSERTING AND :new.STxtID IS NULL THEN
SELECT StringText_STxtID_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 (STxtID), 0) INTO v_newVal FROM StringText;
v_newVal := v_newVal + 1;
--set the sequence to that value
EXECUTE IMMEDIATE ('DROP SEQUENCE StringText_STxtID_SEQ');
EXECUTE IMMEDIATE ('CREATE SEQUENCE StringText_STxtID_SEQ START WITH '||to_char(v_newVal));
END IF;
-- assign the value from the sequence to emulate the identity column
:new.STxtID := v_newVal;
END IF;
END;
/
序列是数据库对象。您无法重置它们,您必须删除并重新创建它们。因此,您必须(ab)为此作业使用动态SQL。
这不是创建自动生成的顺序整数主键列值的最佳做法。此外,请考虑禁止本栏目的手动条目,因为这些条目肯定会按照您尝试维护的顺序造成混乱。