i try to create a trigger to prevent the insertion of duplicate entries in SQL Developer (Oracle 11g XPRESS) but it ‘s not compiled correctly. Can you help me why because I can’t see any obvious error in syntax.
CREATE OR REPLACE TRIGGER trig1
BEFORE INSERT ON table1
BEGIN
DECLARE CURSOR C1
IS
SELECT value1,value2 FROM inserted;
DECLARE value11 number;
DECLARE value22 number;
OPEN C1;
FETCH NEXT FROM C1 INTO @value11, @value22;
WHILE FETCH_STATUS = 0
LOOP
IF NOT EXISTS (SELECT * FROM table1 WHERE value1 = @value11 AND value2 = @value22)
THEN
INSERT INTO table1 (value1,value2)
VALUES
(@value11, @value22);
ELSE
ROLLBACK TRANSACTION
--DELETE FROM table1 WHERE value1 = @value11 AND value2 = @value22
PRINT 'Cannot add duplicate entry.'
END IF;
FETCH NEXT FROM C1 INTO @value11, @value22;
END LOOP;
CLOSE C1;
END;
Most of the problems with your trigger are down to you using the wrong syntax; this looks like MySQL not PL/SQL. I would recommend reading the documentation and looking at some examples before continuing.
Having said all that; you’re going about this all the wrong way. In order to prevent the insertion of duplicates you have to create a unique constraint on your table. It is the only way to guarantee that you prevent them; trying to work around it in code is bound to fail at some point.
You can create a unique constraint inline, or if your table already exists you could create a unique index:
or use an ALTER TABLE statement:
If the set of columns you’re testing against are the primary key you can add a primary key constraint instead.
In addition to enforcing integrity no matter what your users decide enabling a unique constraint enables you to simply insert data and catch the errors. There’s no need to query the table prior to insertion, which should speed up your application.