Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get value from select query in trigger in mysql5?

How to get value from select query in trigger and insert that value in table?

like image 780
Yugal Avatar asked Feb 18 '11 12:02

Yugal


People also ask

Can we use trigger with select statement?

The trigger event that initiates the trigger action can be an INSERT, DELETE, UPDATE, or a SELECT statement. The MERGE statement can also be the triggering event for an UPDATE, DELETE, or INSERT trigger.

Does mysql5 7 support triggers?

MySQL 5.7 does not support triggers using FOR EACH STATEMENT .

How do you insert values into a table using triggers?

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.

How do you declare a variable in trigger?

CREATE TRIGGER Update_estimate_from_line_items AFTER UPDATE ON estimate_line_items FOR EACH ROW BEGIN -- variable declarations DECLARE vPrev_amnt INT; DECLARE vNew_amnt INT; DECLARE nDiff INT; SET vPrev_amnt = OLD. price * OLD. quantity; SET vNew_amnt = NEW.


1 Answers

For an INSERT Trigger query you would use the object NEW
For an UPDATE Trigger query you would use the object OLD and NEW
For a DELETE Trigger query you would use the object OLD

Example 1 : iF you ran INSERT INTO mytable (num) VALUES (10);
In the INSERT trigger, you reference the column as NEW.num (10);

Example 2 : iF you ran UPDATE mytable SET num = 41 WHERE num = 10;
In the UPDATE trigger, you reference OLD.num (10) and NEW.num (41)

Example 3 : iF you ran DELETE mytable num = 104;
In the DELETE trigger, you reference OLD.num (104)

Use something like this:

DELIMITER $$

create trigger my_trigger
AFTER UPDATE on my_update_table
for each row
begin

    DECLARE P1,P2 VARCHAR(50);

    SELECT PRICENAME INTO P1 FROM PRICEIES WHERE PRICEID=OLD.PRICEID;
    SELECT PRICENAME INTO P2 FROM PRICEIES WHERE PRICEID=NEW.PRICEID;
    INSERT INTO AUDITLOG(OLDVALUE, NEWVALUE) VALUES (P1,P2);

end $$

DELIMITER ;
like image 64
RolandoMySQLDBA Avatar answered Nov 10 '22 22:11

RolandoMySQLDBA