tags:

views:

42

answers:

1

I have a exception to prevent inserting same records on my oracle.

If a record having spcific Key value already exists, record insertion interface has to be enabled.

I've heard that COUNT(*) has lots of cost which I don't want to use.

Is there any alternative way to make it at least cost?

+4  A: 

There are two choices

BEGIN
  INSERT INTO table (pk_col, col_a, col_b) VALUES (:pk, :col_a, :col_b);
EXCEPTION
  WHEN DUP_VAL_ON_INDEX THEN
    UPDATE table SET col_a = :col_a, col_b = :col_b WHERE pk_col = :pk;
END;

or

BEGIN
  UPDATE table SET col_a = :col_a, col_b = :col_b WHERE pk_col = :pk;
  IF SQL%ROWCOUNT = 0 THEN
    INSERT INTO table (pk_col, col_a, col_b) VALUES (:pk, :col_a, :col_b);
  END IF;
END;

I've shown a PL/SQL code snippet since you don't specify a client language (eg PHP, Python...). You may handle exceptions and/or checking SQL%ROWCOUNT differently.

Gary
+1 However, the second option isn't 100% reliable - it can fail with a primary key violation if 2 sessions try to insert the same key value concurrently.
Tony Andrews
I'm working on JAVA / JSP and I'm supposed to check it then app's gonna make the button disable which inserts a record
KIM