从查询中使用START WITH创建序列

时间:2010-08-11 17:45:01

标签: oracle plsql sequence oracle9i ora-01722

如何创建一个我的START WITH值来自查询的序列?

我正在尝试这种方式: CREATE SEQUENCE "Seq" INCREMENT BY 1 START WITH (SELECT MAX("ID") FROM "Table");

但是,我收到了ORA-01722错误

2 个答案:

答案 0 :(得分:39)

START WITH CLAUSE接受一个整数。您可以动态形成“创建序列”语句,然后使用execute immediate执行它以实现此目的。

declare
    l_new_seq INTEGER;
begin
   select max(id) + 1
   into   l_new_seq
   from   test_table;

    execute immediate 'Create sequence test_seq_2
                       start with ' || l_new_seq ||
                       ' increment by 1';
end;
/

查看这些链接。

http://download.oracle.com/docs/cd/B14117_01/server.101/b10759/statements_6014.htm
http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/executeimmediate_statement.htm

答案 1 :(得分:-1)

我在这里有一个很好的例子:

declare
 ex number;
begin
  select MAX(MAX_FK_ID)  + 1 into ex from TABLE;
  If ex > 0 then
    begin
            execute immediate 'DROP SEQUENCE SQ_NAME';
      exception when others then
        null;
    end;
    execute immediate 'CREATE SEQUENCE SQ_NAME INCREMENT BY 1 START WITH ' || ex || ' NOCYCLE CACHE 20 NOORDER';
  end if;
end;