Create a Sequence with START WITH from Query
Asked Answered
H

2

17

How can I create a Sequence where my START WITH value comes from a query?

I'm trying this way: CREATE SEQUENCE "Seq" INCREMENT BY 1 START WITH (SELECT MAX("ID") FROM "Table");

But, I get the ORA-01722 error

Hyalite answered 11/8, 2010 at 17:45 Comment(0)
D
46

The START WITH CLAUSE accepts an integer. You can form the "Create sequence " statement dynamically and then execute it using execute immediate to achieve this.

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;
/

Check out these links.

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

Discourtesy answered 11/8, 2010 at 18:0 Comment(1)
I had a little problem when the table is new because "max(id)" returns null. So I had to change the select to: "select nvl(max(id),0) + 1" Maybe someone else runs into the same problemBaht
E
-1

Here I have my example which works just fine:

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;
Esquimau answered 29/5, 2013 at 10:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.