sqloracleoracle11gora-00001

Problem with the trigger created(Fro primary key sequence)


I have created a sequence starting with 1 with no max value I have created a trigger for primary key insertion automatically which is below I have also set a constraint for the table where primary key must be unique and not null

create trigger MY_TEMP_TRIGGER
before insert on MY_TEMP
for each row

BEGIN

  SELECT MY_TEMP_SEQ.nextval 
    INTO :new.Id 
    FROM DUAL;

END;
/

INSERT INTO my_temp  
  (Id,Type, CreateDT, TypeId, TempType, DevType, Msg, File,User, Src, SrcDev)   
VALUES
 (MY_TEMP_SEQ.nextval,3434,2843,2453,2392,435,2390,'pension.txt','rereee',454545,3434)

Result:

ERROR at line 1:
ORA-00001: unique constraint (USER.PK_MY_TEMP) violated

The table MY_TEMP already contains values starting from 1 to 338 fro Id field

So,how should i handle this in triggers and in my insert statements.


Solution

  • You can increment your sequence before you install the trigger:

    declare 
      v_max_id my_temp.id%type;
      v_curr_seq  NUMBER;
    begin
      select max(id) into v_max_id from my_temp;
    
      loop
        select MY_TEMP_SEQ.nextval into v_curr_seq from dual;
        exit when v_curr_seq >= v_max_id;
      end loop;
    end;
    /