Home » SQL & PL/SQL » SQL & PL/SQL » Re: Find record, that causes DUP_VAL_ON_INDEX
Re: Find record, that causes DUP_VAL_ON_INDEX [message #39440] Wed, 17 July 2002 10:33
Todd Barry
Messages: 4819
Registered: August 2001
Senior Member
This assumes:
1) The dup_val_on_index will never be caused by the primary key (otherwise you wouldn't know which unique constraint was being violated)
2) The value that is trying to be inserted for the unique column is available as a variable

sql>create table test (pk int primary key, uniq int not null unique);
 
Table created.
 
sql>declare
  2    v_pk    test.pk%type;
  3    v_uniq  test.uniq%type;
  4  begin
  5    for i in 1..4 loop
  6      if i < 4 then
  7        v_uniq := i * 10;
  8      else
  9        v_uniq := 20;  -- force a unique violation
 10      end if;
 11      insert into test (pk, uniq) values (i, v_uniq);
 12    end loop;  
 13  exception
 14    when dup_val_on_index then
 15      select pk
 16        into v_pk
 17        from test
 18       where uniq = v_uniq;
 19      dbms_output.put_line('Attemped to enter: ' || v_uniq || '  Already exists for pk: ' || v_pk);
 20  end;
 21  /
 
Attemped to enter: 20  Already exists for pk: 2
 
PL/SQL procedure successfully completed.
Previous Topic: => means what
Next Topic: sql report
Goto Forum:
  


Current Time: Fri Apr 19 03:30:26 CDT 2024