重置自动增量序列pl-sql

时间:2011-09-20 14:31:52

标签: oracle plsql auto-increment

如何重置自动增量主键?

我有一个doc_id_seq和一个doc_pk_trg触发器:

CREATE SEQUENCE doc_id_seq START WITH 1;

CREATE OR REPLACE TRIGGER doc_pk_trg
BEFORE INSERT ON TFIDF FOR EACH ROW
BEGIN  
 IF :NEW.doc_id IS NULL THEN    
   SELECT doc_id_seq.NEXTVAL INTO :NEW.doc_id FROM DUAL;  
     END IF;
     END;
 /

我想学习重置序列。我怎样才能做到这一点 ?

3 个答案:

答案 0 :(得分:4)

您可以使用ALTER SEQUENCE语法。

Tom Kyte在这里解释了如何做到这一点:

http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:1119633817597

答案 1 :(得分:2)

只需删除然后重新创建序列。

答案 2 :(得分:1)

这是我重置它的方式

CREATE OR REPLACE PROCEDURE reset_sequence (
   p_sequence_name   IN   VARCHAR2,
   p_new_value       IN   NUMBER
)
AS
   l_current_value     NUMBER;
   v_sequence_exists   NUMBER;
BEGIN
   SELECT 1
   INTO   v_sequence_exists
   FROM   user_sequences
   WHERE  sequence_name = p_sequence_name;

   EXECUTE IMMEDIATE 'SELECT ' || p_sequence_name || '.nextval FROM dual'
   INTO              l_current_value;

   /*Not possible to increment by 0 !*/
   IF (p_new_value - l_current_value - 1) != 0
   THEN
      EXECUTE IMMEDIATE    'ALTER SEQUENCE '
                        || p_sequence_name
                        || ' INCREMENT BY '
                        || (p_new_value - l_current_value - 1)
                        || ' MINVALUE 0';
   END IF;

   EXECUTE IMMEDIATE 'SELECT ' || p_sequence_name || '.nextval FROM dual'
   INTO              l_current_value;

   EXECUTE IMMEDIATE 'ALTER SEQUENCE ' || p_sequence_name || ' INCREMENT BY 1 ';
EXCEPTION
   WHEN NO_DATA_FOUND
   THEN
      raise_application_error (-20001, 'Sequence does not exist');
END;

这比drop& amp;重新创建不会使任何依赖模式对象失效。