Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Trigger to update table in another database

im using the following trigger to update the user table in another database in mysql 5.0.7 The creation of trigger gives no error but upon updating the user table in the first database the trigger is not working. Any suggestions?

DELIMITER $$         
DROP TRIGGER IF EXISTS after_update_user;

CREATE TRIGGER after_update_user;

AFTER UPDATE ON db_test.user  FOR EACH ROW;
BEGIN
    UPDATE TABLE db_testplus.user;
    SET  name = NEW.name;

    WHERE id = NEW.id;
END

$$
DELIMITER ;

I also used this code without the semicolons but still the same

DELIMITER $$         
DROP TRIGGER IF EXISTS after_update_user

CREATE TRIGGER after_update_user

AFTER UPDATE ON db_test.user  FOR EACH ROW
BEGIN
    UPDATE TABLE db_testplus.user
    SET  name = NEW.name

    WHERE id = NEW.id
END;

$$
DELIMITER ;

Finally the code that worked

delimiter |
DROP TRIGGER IF EXISTS after_update_user|
 CREATE TRIGGER after_update_user AFTER UPDATE ON db_test.user
  FOR EACH ROW BEGIN
     UPDATE db_testplus.user SET name = NEW.name WHERE id = NEW.id;
  END;
|
delimiter ;
like image 383
Abhishek Avatar asked Jan 18 '12 13:01

Abhishek


People also ask

How do I insert a trigger into another table?

To create a trigger, we need to change the delimiter. Inserting the row into Table1 activates the trigger and inserts the records into Table2. To insert record in Table1. To check if the records are inserted in both tables or not.

Can we use update in trigger?

AFTER UPDATE Trigger in SQL is a stored procedure on a database table that gets invoked or triggered automatically after an UPDATE operation gets successfully executed on the specified table. For uninitiated, the UPDATE statement is used to modify data in existing rows of a data table.

What is instead of update trigger?

An INSTEAD OF trigger is an SQL trigger that is processed “instead of” an SQL UPDATE, DELETE or INSERT statement. Unlike SQL BEFORE and AFTER triggers, an INSTEAD OF trigger can be defined only on a view, not a table.


2 Answers

Could you please check below

AFTER UPDATE ON db_test.user  FOR EACH ROW
BEGIN
    UPDATE TABLE db_testplus.user
    SET  name = NEW.name

    WHERE id = NEW.id
END;
like image 91
Fahim Parkar Avatar answered Sep 21 '22 06:09

Fahim Parkar


Try this;

CREATE TRIGGER after_update_user

AFTER UPDATE ON db_test.user  FOR EACH ROW
  UPDATE TABLE db_testplus.user
  SET  name = NEW.name
  WHERE id = NEW.id;

Omitting begin-end keywords worked for me.

like image 26
Korhan Ozturk Avatar answered Sep 22 '22 06:09

Korhan Ozturk