当序列增加到一定值时利用pl/sql代码块回到某一值

例题如:

现有一序列SEQ_Order,其起始值为100,其值增长步长被设定为1,经一段时间使用后,当前的CURRVAL值为235,现希望在不删除序列的情况下将其CURRVAL值设置为100,并使值增长步长仍为1,以供后期使用。请写出操作步骤(可有多个步骤,不一定只在一个PL/SQL程序中完成所有工作),并写出操作步骤中使用的PL/SQL程序。 (涉及序列时步长只能在1和-1之间选择)

所需知识点:

pl/sql代码块的into

步骤

第一步:

建立序列,起始值为100,自增长为1。

create sequence seq_order
       increment by 1
       start with 100;
       
   /*刚创建序列时需要next一下才可以用currval查看当前序列号*/     
select seq_order.nextval from dual; 
select seq_order.currval from dual;

第二步:

利用循环使其值增长到235。

declare 
  v_currval number;
begin
  for i in 1..135 loop
    select seq_order.nextval into v_currval from dual;  
    //into 在这里的作用是将查询到的结果转换为number类型的以便于输出。
    dbms_output.put_line('值为:'||v_currval);
    end loop;
end;
/

这时序列的值为235.

第三步:

改变自增量为-1再利用循环使之值为100

(注意起始值不允许改变所以只能改变增量值)
?以下为改变增量为-1

alter sequence seq_order
      increment by -1;
select seq_order.currval from dual;

?以下为用for循环使其值回到100

declare
  v_currval number;
begin
  for i in 1..135 loop
    select seq_order.nextval into v_currval from dual;
    dbms_output.put_line('值为:'||v_currval);
    end loop;
end;
/

这时的值回到了100,可以利用以下语句查询一下:

select seq_order.currval from dual;

值为100

第四步:

再将其增量改为1.

alter sequence seq_order
      increment by 1;

?大功告成?

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章