Ok. So you
do want a unique constraint.
Then this makes a whole lot more sense :)
You don't really need a trigger for that.
A UNIQUE key would be far easier to use.
For example:
-
mysql> CREATE TABLE uniqueTest(
-
-> employee_id Int Not Null,
-
-> place VarChar(50) Not Null,
-
-> UNIQUE `uk_id_place` (employee_id, place)
-
-> );
-
Query OK, 0 rows affected (0.00 sec)
-
-
mysql> INSERT INTO uniqueTest VALUES (1, 'hello');
-
Query OK, 1 row affected (0.00 sec)
-
-
mysql> INSERT INTO uniqueTest VALUES (1, 'hello');
-
ERROR 1062 (23000): Duplicate entry '1-hello' for key 1
-
Is that what you need?
If you
want to do this using a trigger, that is possible to.
And your code isn't far off.
There are a lot of errors in that code however.
First of all, you don't need to INSERT the data manually. Unless the trigger prevents it, the new data will be inserted automatically once the trigger has been executed.
The first line of your code has an extra ON clause that will cause an error.
Check out the
CREATE TRIGGER syntax in the manual.
RAISEERROR is a non-standard function that is not used in MySQL.
Unfortunately the standard equivalent for it, the SIGNAL statement, won't be implemented until MySQL 5.2 (as far as I know).
Until then you will have to
trigger an error by executing a statement that will cause an error.
I like using the CALL statement, using the error message as the procedure name.
Like:
-
mysql> CALL `Duplicate row inserted.`;
-
ERROR 1305 (42000): PROCEDURE skjol.Duplicate row inserted. does not exist
-
Using this inside a trigger would cause an error and effectively terminate the insert statement.
You would want your code to be something like:
-
CREATE TRIGGER triggerName
-
BEFORE INSERT ON targetTable
-
FOR EACH ROW
-
BEGIN
-
IF /* The row already exists */ THEN
-
CALL 'Can not insert duplicate row';
-
END IF;
-
END
-