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.
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:
This assumes that columns
a,bandcare sufficient to uniquely identify the row. I’ve renamed the trigger and procedure to more accurately reflect what/when they are relevant;delis not all that appropriate as a prefix for something called onINSERT.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 likeSELECT a, b, c FROM table1 GROUP BY a, b, c HAVING COUNT(*) > 1.)