srinath
srinath

Reputation: 2998

Informix trigger for deleting one record

When I perform an task, two rows gets inserted in my table ie. duplication. I need to remove the duplicate by using an after insert trigger. I need to delete one duplicate record from those 2. I need something like this

CREATE TRIGGER del_rec
INSERT ON table1
AFTER(EXECUTE PROCEDURE del_proc());

CREATE PROCEDURE del_proc()

//check field a,b,c of this table already exists for this id. if yes delete the second one

END PROCEDURE;

For example:

table 1:

a b c d e
1 1 1 2 2
1 1 1 2 2

it should delete the second row.

Upvotes: 2

Views: 1713

Answers (2)

Joe R.
Joe R.

Reputation: 2042

Why not just use SELECT UNIQUE to avoid inserting duplicate values, or to remove duplicate values which already exist in the table?

Upvotes: 1

Jonathan Leffler
Jonathan Leffler

Reputation: 753675

Your table is misdesigned if duplicates can be inserted into it. You should have a unique constraint ensuring that it does not happen.

Assuming that you can't fix the table for some reason, then:

CREATE TRIGGER ins_table1
    INSERT ON table1 REFERENCING NEW AS new
    FOR EACH ROW (EXECUTE PROCEDURE ins_table1(new.a, new.b, new.c));

This assumes that columns a, b and c are sufficient to uniquely identify the row. I've renamed the trigger and procedure to more accurately reflect what/when they are relevant; del is not all that appropriate as a prefix for something called on INSERT.

CREATE PROCEDURE ins_table1(new_a INTEGER, new_b INTEGER, new_c INTEGER)

    DEFINE l_a LIKE table1.a;

    FOREACH SELECT a INTO l_a
              FROM table1
             WHERE a = new_a AND b = new_b AND c = new_c
       RAISE EXCEPTION -271, -100;
    END FOREACH;

END PROCEDURE;

This is called for each row that's inserted. If the SELECT statement returns a row, it will enter the body of the FOREACH loop, so the exception will be raised and the INSERT will be aborted with a more or less appropriate error (-271 Could not insert new row into the table; -100 ISAM error: duplicate value for a record with unique key).

If you try to do this validation with an AFTER trigger, you have to scan the entire table to see whether there are any duplicates, rather than just targeting the single key combination that was inserted. Note that in general, an INSERT can have multiple rows (think INSERT INTO Table SELECT * FROM SomeWhereElse). The performance difference will be dramatic! (Your query for an AFTER trigger would have to be something like SELECT a, b, c FROM table1 GROUP BY a, b, c HAVING COUNT(*) > 1.)

Upvotes: 1

Related Questions