oracle 重置自动递增序列pl-sql

j9per5c4  于 2022-11-03  发布在  Oracle
关注(0)|答案(4)|浏览(172)

如何重置自动递增主键?
我有一个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;
 /

我想学习重置序列。我该怎么做呢?

ar7v8xwq

ar7v8xwq1#

您可以使用ALTER SEQUENCE语法。
Tom Kyte在这里解释了如何做到这一点:
http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:1119633817597

juzqafwq

juzqafwq2#

只需删除并重新创建序列。

baubqpgj

baubqpgj3#

这就是我重置它的方法

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;

与删除和重新创建相比,这有一个额外的好处,即不会使任何相关的模式对象失效。

xsuvu9jc

xsuvu9jc4#

试试这个

alter table "table_name"
modify "id" generated always as identity restart start with 1;

相关问题