我不明白为什么这段代码中有一条select语句,为什么它有两倍于alter sequence语句的增量语句
我在asktom网站上找到了这段代码
CREATE OR REPLACE
PACKAGE pkg_seq AS
PROCEDURE alterSequenceLast(
sequenceName IN VARCHAR2,
inc in integer);
END;
/
CREATE OR REPLACE
PACKAGE BODY pkg_asktom AS
PROCEDURE alterSequenceLast(
sequenceName IN VARCHAR2,
inc in integer)
is
stmt VARCHAR2(2000);
l_n number;
begin
BEGIN
-- alter increment to inc
stmt := 'ALTER SEQUENCE ' || sequenceName ||' INCREMENT BY ' ||inc;
dbms_output.put_line('Executing ''' || stmt || '''');
EXECUTE IMMEDIATE stmt;
-- read the next value
stmt := 'SELECT ' || sequenceName || '.NEXTVAL FROM DUAL';
dbms_output.put_line('Executing ''' || stmt || '''');
EXECUTE IMMEDIATE stmt into l_n;
-- alter increment to 1
stmt := 'ALTER SEQUENCE ' || sequenceName ||' INCREMENT BY 1';
dbms_output.put_line('Executing ''' || stmt || '''');
EXECUTE IMMEDIATE stmt;
END;
end alterSequenceLast;
END;
/
执行后,我得到了
SQL> exec pkg_seq.alterSequenceLast('acc_seq',1);
Executing 'ALTER SEQUENCE acc_seq INCREMENT BY 1'
Executing 'SELECT acc_seq.NEXTVAL FROM DUAL'
Executing 'ALTER SEQUENCE acc_seq INCREMENT BY 1'
我会这样做,我会将序列返回到开头。
CREATE OR REPLACE
PACKAGE pkg_seq AS
PROCEDURE alterSequenceLast(
sequenceName IN VARCHAR2,
inc in integer);
END;
/
CREATE OR REPLACE
PACKAGE BODY pkg_seq AS
PROCEDURE alterSequenceLast(
sequenceName IN VARCHAR2,
inc in integer)
is
stmt VARCHAR2(2000);
l_n number;
begin
BEGIN
stmt := 'ALTER SEQUENCE ' || sequenceName ||' restart start with ' ||inc;
dbms_output.put_line('Executing ''' || stmt || '''');
EXECUTE IMMEDIATE stmt;
-- alter increment to 1
stmt := 'ALTER SEQUENCE ' || sequenceName ||' INCREMENT BY 1';
dbms_output.put_line('Executing ''' || stmt || '''');
EXECUTE IMMEDIATE stmt;
END;
end alterSequenceLast;
END;
/
Thak前进,Petar。
答案 0 :(得分:2)
此代码用于将序列设置为从新值开始。
例如,假设我们有一个表,该表通常具有由序列our_seq
生成的ID,但是由于某种原因,我们不使用序列就装入了10000条记录。如果我们插入新记录会怎样?按目前的情况,our_seq.nextval
将生成一个ID,该ID与批量加载的记录的键冲突。
因此,我们需要调整序列的值。一种方法是选择nextval
一万次。或者我们可以
Tom Kyte软件包是使第二种方法自动化的一种方法。我个人认为这是一个有趣的古玩。如果您需要经常执行此操作以使其自动化,那么您可能应该重新考虑数据加载惯例。
[我们]是否可以在不选择语句的情况下增加10001的顺序?
不。唯一受支持的方法是删除序列,然后从所需的起始值开始重新创建序列。由于授权,代码无效等原因,删除对象更加复杂。
假设您的兴趣是您拥有一个当前值= 10001的序列,并且想要重置它,以便它再次从1开始,您将传递负增量-10001。注意不要将其递减到minvalue
(默认为1)以下;在发出nextval
之前,数据库不会警告您或抛出错误,此时它会告诉您:
ORA-08004: sequence OUR_SEQ.NEXTVAL goes below MINVALUE and cannot be instantiated