SQL Trigger to update OLD value in another table - mysql

I am trying to create a trigger to simultaneously update a different table than the one I have updated, with the same data.
I have two different database with the same tables and i'm trying to sync them, when i insert, update or delete data from one, i want to do automaticaly the same to the other table, with triggers.
This is the trigger code:
CREATE DEFINER=`Ivan_test`#`%` TRIGGER `Prueba_Ivan`.`mag_articulos_PI_AFTER_UPDATE` AFTER UPDATE ON `mag_articulos_PI` FOR EACH ROW
BEGIN
IF OLD.Prueba_Ivan.mag_articulos_PI NOT IN (SELECT * FROM ivan_test.mag_articulos_IT) THEN
INSERT INTO ivan_test.mag_articulos_IT
VALUES (new.xempresa_id, new.xarticulo_id, new.xcategoria_id, new.xvisible_web, new.xnovedad,new.xpromocion,new.ximagen_prelim,new.ximagen_amp,new.xtexto1,new.xtexto2,new.xtexto3,new.xtexto4,new.xtexto5);
ELSE
UPDATE ivan_test.mag_articulos_IT SET OLD.ivan_test.mag_articulos_IT = NEW.Prueba_Ivan.mag_articulos_PI;
END IF;
END
but I have this error:
Error Code: 1109. Unknown table 'OLD.Prueba_Ivan' in IN/ALL/ANY subquery
Can someone help me to find the mistake?
Thank you!!

OLD.Prueba_Ivan.mag_articulos_PI
OLD is an alias to the triggered row. Your trigger applies to Prueba_Ivan, which means that OLD and NEW are representing your Prueba_Ivan record before the change, and after it, respectively. This means that when you intend to reference mag_articulos_PI, you will need to do it via OLD.mag_articulos_PI, so remove the tablename from that expression.
OLD.ivan_test.mag_articulos_IT
As mentioned in the previous section, here OLD is an alter-ego of the updated Prueba_Ivan record, you do not need it in order to reference ivan_test.
Further explanation
An expression of the form of
a.b.c
reads as follows:
In database a, table b, column c. When you do something of the like of
OLD.t.c
it reads: In the OLD database, table t, column c.

Related

MySQL: How to pass parameter to a trigger

I have a table on a mysql 5.7 db, containing say athletes with their mean, max, avg times in a specific sport. I have another table that lists some calculated statistics based on those values.
I managed to do the calculcations that end up on the second using stored procedures. I use as input parameter to the stored procedure the athlete's name.
So when in the first table, an athlete is inserted (with his/her avg/min/max times) or his/her values are updated and I run the stored procedure, the later updates the statistics table.
My question is how to achieve the same result with triggers?
I guess it is feasible/easy to update the entire table on each insert or update of the first table. What would be more efficient performance-wise, would be on each :
INSERT into table1 values (..) where athlete_name="John Do"
(...)
ON DUPLICATE KEY UPDATE (...)
Run a trigger in the pseudocode form :
INSERT into statistics_table values (..) where athlete_name="John Do"
ON DUPLICATE KEY UPDATE (...)
How can the the athlete_name="John Do" be passed to the trigger dynamically, to avoid update the entire statistics table?
You cannot pass any parameters to a trigger and the insert statement does not support the where clause either.
Having said this, a trigger can pick up the user's name from the record being inserted / updated / deleted using NEW.athlete_name or OLD.athlete_name (whichever is required) and use that to call a stored procedure:
Within the trigger body, the OLD and NEW keywords enable you to access
columns in the rows affected by a trigger. OLD and NEW are MySQL
extensions to triggers; they are not case-sensitive.
In an INSERT trigger, only NEW.col_name can be used; there is no old
row. In a DELETE trigger, only OLD.col_name can be used; there is no
new row. In an UPDATE trigger, you can use OLD.col_name to refer to
the columns of a row before it is updated and NEW.col_name to refer to
the columns of the row after it is updated.
A column named with OLD is read only. You can refer to it (if you have
the SELECT privilege), but not modify it. You can refer to a column
named with NEW if you have the SELECT privilege for it. In a BEFORE
trigger, you can also change its value with SET NEW.col_name = value
if you have the UPDATE privilege for it. This means you can use a
trigger to modify the values to be inserted into a new row or used to
update a row. (Such a SET statement has no effect in an AFTER trigger
because the row change will have already occurred.)
You can create triggers that fire after each insert or update on the parent table (athletes). Within each trigger, you can access the value of column athlete_name on the record that was just created or changed, and then invoke your stored procedure using CALL().
Here is a code sample for such an INSERT trigger :
CREATE TRIGGER athletes_upd AFTER INSERT ON athletes
FOR EACH ROW
BEGIN
CALL my_procedure(NEW.athlete_name);
END;
UPDATE trigger :
CREATE TRIGGER athletes_upd AFTER UPDATE ON athletes
FOR EACH ROW
BEGIN
CALL my_procedure(NEW.athlete_name); -- or maybe OLD.athlete_name ?
END;

What is proper way to set and compare variable inside an sql trigger

Am populating a table using a trigger after an insert event occurs on another table and that worked fine. However i then noticed that the trigger would still insert a new row for existing records. To fix this, I want to create the trigger again but this time it would only fire if a condition is met...but not having previously used triggers in the past am getting a syntax error and not able to identify what am doing wrong. Kindly have a look and help me fix this
CREATE TRIGGER `students_gen_insert`
AFTER INSERT ON `students` FOR EACH ROW
BEGIN
INSERT INTO records (student_id, subject_id)
SELECT new.student_id, subjects.subject_id
FROM subjects
WHERE category = new.class;
END;
Am currently using MySql 5.6.17 version.
It is generally not a good idea to SELECT from the table the trigger is on, and forbidden to UPDATE or INSERT (not that you are doing those). Assuming you are trying to get the values for the row just inserted, the first SET ... SELECT you have is needless; just use NEW.fieldname to get the fields of the inserted row.
The second SET ... SELECT and following condition are a bit confusing. If referential integrity is being maintained, I would think it would be impossible for the records table to refer to that particular student_id of the students table at the point the trigger is executed. Perhaps this was to avoid the duplicate inserts from the trigger's previous code? If so, it might help for you to post that so we can pinpoint the actual source of redundant inserts.

whenever i update my table i want to store my old data(old-row) in a new table

CREATE TRIGGER items_
ON test
after update
AS
begin
INSERT INTO test2(id,namecan)
SELECT id,namecan from test
end
I Have tried with trigger but i didnt get any results so please help me how to deal with it
methods involving two stored procedures are also welcome
You could do it with a stored procedure, but I would use a trigger.
With a stored procedure, I'd perceive you using a cursor on the otherDatabase table to read through the records and compare each with the values in Table1 to determine whether Table1's data needed to be written to Table2, and if so, to do it.
With a trigger, I would simply update the data in Table1 by whatever means, without concerning myself with what the overwriting data is, and in the trigger,
use the old and new values using the ##Inserted & ##Deleted (system) tables to determine if the old values (##Deleted) needed to be written to Table2.
If you don want to use triggers, you can go for this concept..
Let there is a form from which you are inserting the values on a table say register table. And the action of the form in going to servlet MyServlet. In Myservlet
you can first fetch the data from the Register table and store it into the Rsultset object let rs. And after that insert the rs into a new table.
Please let me know if m not clear to u..
Your trigger syntax is wrong
delimiter //
CREATE TRIGGER items_ after update
ON test
for each row
begin
INSERT INTO test2(id,namecan) values (old.id,old.namecan);
end; //
delimiter ;
So this trigger will make an entry to the test2 table every time you update row in the test table with the old row values from test table.
You should call old.id and old.namecan (i assume that table 'test' have 'id' and 'namecan' field)to get the older data. your trigger body should look like this
begin
INSERT INTO test2(id,namecan) value(old.id, old.namecan)
end
'old' will reference to record which you update.

MySQL Trigger - INSERT on condition of UPDATE

I'm trying to find the most effecient way of inserting data into another table when a particular field is updated on trigger table. The INSERT should only occur on a specific type of update.
The table on which I want to create the trigger is named incremental. The table I'm inserting into is named crm_record
On incremental there is a field called status. By default when a record is initially added to the table the status field is set to new. After billing has processed that value changes to processed. So once this occurs I want to INSERT into crm_record, only if the value of another field (success) is set to 1.
I have considered using both CASE and IF but would like an expert's opinion on the best way to do this.
Ok, I eventually went with this that seemed to work. Thanks for pointing me in the right direction
CREATE TRIGGER `incremental5_after_ins_tr_crmm` AFTER UPDATE ON `incremental5`
FOR EACH ROW
BEGIN
IF Status = 'processed' AND Success = 1 THEN
INSERT INTO crm_master (msisdn,source,contract_type,revenue) VALUE (new.msisdn,'INC5',new.contract_type,revenue=revenue+2.5)
ON DUPLICATE KEY UPDATE contract_type=new.contract_type,revenue=revenue+2.5;
END IF;
END;
All you need to do is to create an AFTER UPDATE trigger and test the value of status and success together. If it's going only going to be one state you're testing for then an IF statement would be the simplest way to go about it.
However before implementing a trigger it's always worth going back a step and checking to see if the row in crm_record shouldn't actually be inserted via the code logic when the status and success columns are updated.

To check values in other databases using trigger

Is it possible to check whether a particular value in a column exists in other databases using trigger? These two databases are located inside the same MYSQL instance. Specifically, what I want to do is this:
Before a row is added to a table ( Document_Index_table) inside Database A ( Document_DB).
A trigger is fired. This trigger carries the one of the column value (usr_id) inside the row and pass it to Database B ( User_Control_DB).
Based on the values, User_Control_DB will check whether the usr_id exists in column usr_id of the table (Usr_Information).
If exists, then return a true to Document_DB and the row in 1. is allowed to add to the Document_DB.
If not, then an error is issued. No row is added to Document_DB.
How can this be done, if it can be done at all?
Edit: Both databases are MySQL databases
So, I'm a complete novice at database development, but you could do something like this:
Create a 'Before' insert trigger on your document_index_table.
The trigger does something like this:
declare numRows integer;
select count(*) from user_control_db.usr_information where usr_id = NEW.usr_id into num_rows;
if (numRows > 0) then
call NonExistentProc();
end if;
I believe that this would accomplish what you wanted. It'll produce an error like "PROCEDURE documentdb.NonExistenProc does not exist" and skip the insert if there isn't at least one row that has the matching usr id in the user control db.
Again, I'm a novice at this DB stuff so there might be a more elegant way, but this worked for my single test case.
Hope that helps.