views:

147

answers:

2

I am trying to set up a MySQL trigger that does the following:

  • When someone inserts data into databaseA.bills, it verifies if databaseB.bills already has that row, if it doesn't, then it does an additional insert into databaseB.bills.

Here is what I have:

CREATE TRIGGER ins_bills AFTER INSERT ON databaseA.bills
FOR EACH ROW
  BEGIN
    IF NOT EXISTS (SELECT 1 FROM databaseB.bills WHERE billNumber=NEW.billNumber) THEN
      INSERT INTO databaseB.bills (billNumber) VALUES (NEW.billNumber)
    END IF
  END;//
DELIMITER ;

The problem is, I can't create it through mysql console or phpMyAdmin. It returns syntax errors near END IF END, and I am sure it's a delimiter problem.

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'END IF END' at line 6

What am I doing wrong?

+1  A: 

Assuming you are using // as your delimiter, you just need to use semi-colons at the end of the sql stmts inside the body of the trigger, and use // after the trigger END:

CREATE TRIGGER ins_bills AFTER INSERT ON databaseA.bills
FOR EACH ROW
  BEGIN
    IF NOT EXISTS (SELECT 1 FROM databaseB.bills WHERE billNumber=NEW.billNumber) THEN
      INSERT INTO databaseB.bills (billNumber) VALUES (NEW.billNumber);
    END IF;
  END //
Ike Walker
+1  A: 

If you have unique indexes you always can make an INSERT IGNORE

 CREATE TRIGGER ins_bills AFTER INSERT ON databaseA.bills
    FOR EACH ROW
      BEGIN
          INSERT IGNORE INTO databaseB.bills (billNumber) VALUES (NEW.billNumber);
      END //
Luis Melgratti
Well I ended up using this shorter query, since yeah, billNumber was a unique index. All the other answer were also correct though.
Danny Herran