Reset auto increment sequence pl-sql

▼魔方 西西 提交于 2019-12-24 02:21:42

问题


How can i reset auto increment primary key ?

I have a doc_id_seq and a doc_pk_trg trigger like that:

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;
 /

I want to learn reset the sequence . How can I do this ?


回答1:


You could use the ALTER SEQUENCE syntax.

Tom Kyte explains how to do exactly this here:

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




回答2:


Simply drop and then recreate the sequence.




回答3:


This is how I would reset it

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;

This has the added benefit over drop & recreate of not invalidating any dependant schema objects.



来源:https://stackoverflow.com/questions/7486917/reset-auto-increment-sequence-pl-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!