0

users(id,company,name)

This is my schema for the table. How should i write a trigger to check for the duplicates before inserting the new row. I need to check the incoming data is not duplicated with the incoming record. if the incoming record is existing that record should not be inserted to the table. If its not duplicating that record hould be inserted!

Below is the trigger i tried but it gives an error at the 'last end' line

DELIMITER $$
CREATE TRIGGER userDuplicate 
BEFORE INSERT ON `users` FOR EACH ROW

BEGIN
    DECLARE recordId VARCHAR(999);

    SET recordId = (SELECT id FROM users WHERE company= NEW.companyAND name = NEW.name);

    IF recordId IS NOT NULL
    THEN
        INSERT INTO users (company,name) VALUES (NEW.name,NEW.company);
    END IF;
END;
$$ DELIMITER;

1 Answers1

0

According to the accepted answer here: How to abort INSERT operation in MySql trigger? you can not have a MySQL trigger cancel the INSERT. It's easy on PostgreSQL (BEFORE INSERT trigger simply returns NULL), but MySQL can not handle that.

The thing you can do, though, is an INSERT IGNORE:

INSERT IGNORE INTO users (company, name) 
VALUES ('ABC','DEF');
Community
  • 1
  • 1
Boris Schegolev
  • 3,601
  • 5
  • 21
  • 34