我正在尝试创建一个从表中的最大id开始的序列。
我回答了这个先前提出的问题 How to create sequence using starting value from query?
这是顺序:
CREATE SEQUENCE q9_seq;
SELECT setval('q9_seq', (SELECT MAX(department_id) FROM hr_departments));
即时通讯的结果是:
ORA-00923:在预期错误处找不到FROM关键字。
答案 0 :(得分:1)
declare
v_num number;
begin
select nvl(max(value), 0) + 1
into v_num
from table;
execute immediate 'create sequence drop_me_seq start with ' || v_num;
end;
/
答案 1 :(得分:1)
您可以为此使用客户端特定的功能,例如替换变量。在SQL * Plus或SQL Developer中:
column v_start new_value v_start
select nvl(max(department_id), 0) + 1 as v_start from hr_departments;
create sequence q9_seq start with &v_start;
old:create sequence q9_seq start with &v_start
new:create sequence q9_seq start with 43
Sequence Q9_SEQ created.
select q9_seq.nextval from dual;
NEXTVAL
----------
43
或者您可以更改现有的顺序以跳过数字,或致电nextval
直到达到现有的最大值(as here)。
或者您可以使用一个简单的匿名块:
declare
l_start number;
begin
select nvl(max(department_id), 0) + 1 into l_start from hr_departments;
execute immediate 'create sequence q9_seq start with ' || l_start;
end;
/
PL/SQL procedure successfully completed.
select q9_seq.nextval from dual;
NEXTVAL
----------
43
动态SQL语句的生成方式与替换变量方法一样,生成方式为create sequence q9_seq start with 43
。
(这两个都假设您的表的当前最高值为42 ...)