Frage

Based on this example, I created this code:

DECLARE
    new_employee_id INTEGER;
BEGIN
    SELECT MAX(EMP_ID) + 1 INTO new_employee_id FROM EMPLOYEE;
    EXECUTE IMMEDIATE 'CREATE OR REPLACE SEQUENCE primary_key_seq START WITH ' || new_employee_id || ' INCREMENT BY 1';
END;
/

OBS: perhaps using a sequence to auto increment the primary key of a table doesn't make much sense, but this is a school exercise and that's what we're supposed to do, so please disregard that aspect.

This is the error I have: ERROR AT LINE 1 ORA-00922: missing or invalid option ORA-06512: at line 5

What could be wrong?

War es hilfreich?

Lösung

There is no CREATE OR REPLACE SEQUENCE option, so you must use the CREATE SEQUENCE Statement and the a DROP statement if you need to drop it first.

DECLARE
    new_employee_id INTEGER;
BEGIN
    SELECT MAX(EMP_ID) + 1 INTO new_employee_id FROM EMPLOYEE;
    EXECUTE IMMEDIATE 'CREATE SEQUENCE primary_key_seq START WITH ' || new_employee_id || ' INCREMENT BY 1';
END;
/

Andere Tipps

there is no REPLACE in create sequence command check documentation (wich is always a good idea ;-)

should be

DECLARE
    new_employee_id INTEGER;
BEGIN
    SELECT MAX(EMP_ID) + 1 INTO new_employee_id FROM EMPLOYEE;
    EXECUTE IMMEDIATE 'CREATE SEQUENCE primary_key_seq START WITH ' || new_employee_id || ' INCREMENT BY 1';
END;
/

This question begs another question - why are you trying to drop and re-add a sequence? You should never need to do this. Create the sequence once:

CREATE SEQUENCE PRIMARY_KEY_SEQ
  MINVALUE 1
  MAXVALUE 9999999999999999999999999999
  START WITH 1
  INCREMENT BY 1
  NOCACHE;

Then, use it in your code:

DECLARE
  new_employee_id INTEGER;
BEGIN
  new_employee_id := PRIMARY_KEY_SEQ.NEXTVAL;

  INSERT INTO SOME_TABLE_MAYBE_EMPLOYEES
    (ID, WHATEVER, WHATEVER_ELSE)
  VALUES
    (new_employee_id, 'WHATEVER', 'WHATEVER_ELSE');
END;

The whole purpose of the sequence is to provide unique, non-repeating values. Going out to the table, grabbing the MAX(ID), and recreating the sequence to start from there is sort of backwards from the way a sequence should be used. Create a sequence once, then use it many times.

Hopefully this helps.

Share and enjoy.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top