MySQL Trigger - Using logical inserted table to insert into another table - mysql

I am currently in the process of writing my first trigger in MySQL within PHPmyadmin. I would like it so that when an item in one table is updated, a row in another table is inserted. Several columns of the row that is to be inserted in the second table are determined by the values being updated in the first table.
Therefore, I need to INSERT a new row in table B when an update occurs on table A. And some of the values of the columns in table B are to be defined by the values in the updated table A row which caused the trigger to run.
Please find the trigger below.
CREATE TRIGGER `before_categoryiteminstance_update` BEFORE UPDATE ON `TABLEA`
FOR EACH ROW BEGIN
declare f_guidcategoryiteminstance int;
declare f_guidcategory int;
INSERT INTO TABLEB
SET
f_guidcategoryiteminstance =(SELECT guidcategoryiteminstance FROM inserted),
f_guidcategory =(SELECT guidcategory FROM inserted),
guiduser= f_guidcategory,
guidcategoryinstance= f_guidcategoryiteminstance,
number= number +1,
dateofaction= NOW(); END
The trigger can be added to the DB fine. However, when I attempt to update a row on table A (which should cause the trigger to run), I get an error stating that the table Inserted does not exist. However, I was under the impression that Inserted should be a logical table that contains the results of the initial part of the trigger. Is this only the case if the trigger is being run on an insert and not an update? If so, is there an equivalent for an update trigger?

Related

How to use trigger to update only one row in table with Mysql

I have an after insert trigger that is supposed to update the field total in my table "test" where the id_cart is equal to new.id_cart. However my trigger is updating every single row in the table not only the one desired. I would like to know how can I modify my trigger so it only updates the row that I want.
This is my trigger.
CREATE DEFINER=`root`#`localhost` TRIGGER `update_total_test`
AFTER INSERT ON `test_product_quantity_cart`
FOR EACH ROW BEGIN
UPDATE test set total= (select sum(price_product) from test_product_quantity_cart where id_cart=new.id_cart);
END
So if the new row inserted in table "test_product_quantity_cart" has an new.id_cart=1, then only the row in table "test" with id_cart=1 should be uptated.
I think I am missing a "where" clause to indicate the update statement which rows it is suppossed to upate. However I do not know how to add that clause.
Thank you!
CREATE DEFINER=`root`#`localhost` TRIGGER `update_total_test`
AFTER INSERT ON `test_product_quantity_cart`
FOR EACH ROW
UPDATE test
JOIN ( SELECT id_cart, SUM(price_product) total
FROM test_product_quantity_cart
WHERE id_cart=NEW.id_cart ) value_for_update USING (id_cart)
SET test.total = value_for_update.total;

MYSQL Trigger to insert column value in same table

I have a mysql Innodb table 'classrooms_subjects' as
id|classroom_id|subject_id
classroom_id & subject_id are composite keys. Whenever i insert a row with classroom_id & subject_id, my id field is inserted as 0.
Now i want to create a trigger which will enter id field as last_inserted_id()+1.
Also I need to take care of multiple records inserted at a time. My trigger is like below:
CREATE TRIGGER `increment_id` AFTER INSERT ON `classrooms_subjects`
FOR EACH ROW BEGIN
UPDATE classrooms_subjects
SET classrooms_subjects.id = LAST_INSERT_ID() + 1 WHERE id=0;
END
when i am inserting a record I am getting the error as:
"Cant update table in trigger because it is already used by statement which invoked this trigger
For general info: using an update statement inside the trigger isn't right.
Better to use a before insert trigger and simply assign the value of your column using NEW.id
http://dev.mysql.com/doc/refman/5.7/en/trigger-syntax.html
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 should probably structure your table to make the auto_increment work properly. Better a solution that works when multiple sessions are inserting to the DB at once.

MySQL trigger INSERT all NEW columns

Is it possible to trigger the insert of all the columns for the NEW row? Basically, I want to make a copy of the newly insert record in another table but what having to specify all the columns.
Something like
DELIMITER $$
CREATE TRIGGER TestTrigger
AFTER INSERT
ON Table1 FOR EACH ROW
BEGIN
INSERT INTO `Table2` SELECT * FROM NEW;
END$$
DELIMITER ;
However this returns Table 'Database.NEW' doesn't exist whenever I try to insert a new row in Table1.
From MySQL documentation:
Within the trigger body, you can refer to columns in the subject table (the table associated with the trigger) by using the aliases OLD and NEW. OLD.col_name refers to a column of an existing row before it is updated or deleted. NEW.col_name refers to the column of a new row to be inserted or an existing row after it is updated.
Despite the time this question have been unanswered, you can SELECT all fields using primary key in source table if you have one.
CREATE TRIGGER replicated_table AFTER INSERT ON source_table FOR EACH ROW
BEGIN
INSERT INTO replicated_table SELECT * FROM source_table WHERE id=NEW.id;
END
Also, maybe you can prefer the use of REPLACE instead of INSERT to ensure the table will not stay out of sincronization.

MySQL Trigger cannot update table - getting ERROR 1442

I have the following trigger:
CREATE TRIGGER sum
AFTER INSERT
ON news
FOR EACH ROW
UPDATE news SET NEW.sum = (NEW.int_views + NEW.ext_views)/NEW.pageviews
It sums the int_views and ext_views column of a table and divides them by the total pageviews.
Whenever I try to add a new row to news, I get the following error:
ERROR 1442 (HY000) at line 3: Can't update table 'news' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.
The trigger seems pretty simple to me. Is there a reason why the trigger fails to run?
The symptom is, that you are running an UPDATE (for all rows) inside a INSERT trigger - both modify the table, which is not allowed.
That said, if I guess the intention of your trigger correctly, you do not want to update all rows, but only the newly inserted row. You can achieve that easily with
CREATE TRIGGER sum
BEFORE INSERT
ON news
FOR EACH ROW
SET NEW.sum = (NEW.int_views + NEW.ext_views)/NEW.pageviews
Mind that this is a BEFORE INSERT trigger, as you want to change the row before it is written to the table.
If you try to update/insert on the same table that cause trigger to fire do not use the common sql command like
-> UPDATE TABLE_NAME SET COLUMN_NAME = VALUE WHERE CONDITION_LIST;
-> INSERT INTO TABLE_NAME VALUES("VALUE1","VALUE2");
This will not work. Only use set to assign the value of the column you update.
Example:
CREATE TRIGGER trigger_name BEFORE/AFTER INSERT/UPDATE ON table_name
FOR EACH ROW
SET NEW.COLUMN_NAME = "VALUE";
I was in a similar condition where I had to run two triggers:
UPDATE 3 fields on INSERTing a new ROW
UPDATE 3 fields on UPDATEing a ROW
After lot of efforts, I was finally able to write the TRIGGER in following way:
FOR updating values on INSERT
CREATE TRIGGER `INSERT_DISCOUNT_SERVICES` BEFORE INSERT ON `services`
FOR EACH ROW SET
NEW.discount_5_rate = (NEW.ndis_rate*0.05),
NEW.discount_10_rate=(NEW.ndis_rate*0.10),
NEW.discount_15_rate=(NEW.ndis_rate*0.15)
Similarly
FOR updating values on UPDATE
CREATE TRIGGER `UPDATE_DISCOUNTS_SERVICES` BEFORE UPDATE ON `services`
FOR EACH ROW SET
NEW.discount_5_rate = (NEW.ndis_rate*0.05),
NEW.discount_10_rate=(NEW.ndis_rate*0.10),
NEW.discount_15_rate=(NEW.ndis_rate*0.15)

INSTEAD OF UPDATE,DELETE,INSERT : determine each command

I need determine each of this this 3 commands in trigger [UPDATE,DELETE,INSERT].For last 2 I do next:
IF EXISTS (SELECT * FROM inserted)
BEGIN
END
ELSE IF EXISTS (SELECT * FROM deleted)
BEGIN
END
How can I get updating rows?
Thanks.
Not exactly sure what you're trying to accomplish, but you can test if it's an UPDATE if both inserted (values after update) and deleted (values before update) exist. From the documentation:
The deleted table stores copies of the affected rows during DELETE
and UPDATE statements. During the execution of a DELETE or UPDATE
statement, rows are deleted from the trigger table and transferred to
the deleted table. The deleted table and the trigger table ordinarily
have no rows in common.
The inserted table stores copies of the affected rows during
INSERT and UPDATE statements. During an insert or update
transaction, new rows are added to both the inserted table and the
trigger table. The rows in the inserted table are copies of the new
rows in the trigger table.
Thus, if inserted exists but not deleted, it's an INSERT; if deleted exists but not inserted, it's a DELETE; if they both exist, it's an UPDATE.