2010-08-11 13 views
12

¿Cómo puedo crear una secuencia donde mi valor START WITH proviene de una consulta?Crear una secuencia con START WITH from Query

Estoy intentando de esta manera: CREATE SEQUENCE "Seq" INCREMENT BY 1 START WITH (SELECT MAX("ID") FROM "Table");

Pero, me sale el error ORA-01722

Respuesta

35

el comienzo con la cláusula acepta un entero. Puede formar la instrucción "Crear secuencia" dinámicamente y luego ejecutarla usando ejecutar inmediato para lograr esto.

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

Echa un vistazo a estos enlaces.

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

+2

tuve un pequeño problema cuando la mesa es nueva porque "max (id)" devuelve un valor nulo. Así que tuve que cambiar la selección a: "select nvl (max (id), 0) + 1" Tal vez alguien más se encuentre con el mismo problema – steven2308

-1

Aquí tengo mi ejemplo, que funciona muy bien:

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; 
Cuestiones relacionadas