如何在Oracle 10g PL / SQL中获得序列的MINVALUE?

时间:2009-09-03 16:27:48

标签: oracle plsql oracle10g aggregate-functions sequences

我写了一个PL / SQL脚本来将序列的值设置为表的主键的最大值:

DECLARE
  max_idn NUMERIC(18, 0);
  seq_nextval NUMERIC(18, 0);
  increment_amount NUMERIC(18, 0);
BEGIN
  SELECT MAX(mbr_idn)
  INTO max_idn
  FROM mbr;

  SELECT mbr_seq.nextval
  INTO seq_nextval
  FROM DUAL;

  increment_amount := max_idn - seq_nextval;

  EXECUTE IMMEDIATE 
    'ALTER SEQUENCE mbr_seq
     increment by ' || increment_amount;
END;

但是,如果序列的MINVALUE大于最大主键,则会出错:

  

ORA-08004:序列MBR_SEQ.NEXTVAL低于MINVALUE且无法实例化

     

ORA-06512:第10行

最简单的说法是“通过increment_amount递增序列,但不要低于MINVALUE”?

1 个答案:

答案 0 :(得分:3)

您可以查询DBA_SEQUENCES表以获取MIN_VALUE

SELECT min_value
  INTO l_min_value
  FROM all_sequences
 WHERE sequence_name = 'MBR_SEQ'
   AND owner = <<sequence owner>>

然后您可以将其合并到您的代码中,即

increment_amount := GREATEST( max_idn, l_min_value ) - seq_nextval;