search

Home  >  Q&A  >  body text

Create a trigger in a mysql stored procedure

I want to create a trigger in the process. But after some research I found this is not possible. Can you suggest me another way to achieve the following? (For some reason, I cannot share the exact data and query. Please refer to similar queries.)

What do I want

I created a temporary table containing the data I need.

For example. CREATE TEMPORARY TABLE temp1 SELECT id, col_1 FROM table1 WHERE col_1=2;

When data is inserted into temp1, I want to insert data into table table2, I can achieve this by creating TRIGGER. But the problem is that I want to give a value in table2 which will be dynamic and will be fetched from nodejs backend. So I created a PROCEDURE which accepts the parameter neededId . But I can't create a trigger within the program. Is there any other way I can achieve this?

The process I created

Here neededId is the foreign key I get from the backend to insert

DELIMITER $$
USE `DB`$$
CREATE PROCEDURE `MyProcedure` (IN neededID int)
BEGIN
    DROP TABLE IF EXISTS temp1;
    CREATE TEMPORARY TABLE temp1 SELECT id, col_1 FROM table1 WHERE col_1=2;

    
    DROP TRIGGER IF EXISTS myTrigger;
    CREATE TRIGGER myTrigger AFTER INSERT ON temp1 FOR EACH ROW
    BEGIN
        INSERT into table2("value1", "value2", neededId);
    END;
    
END$$

DELIMITER ;

P粉197639753P粉197639753313 days ago487

reply all(1)I'll reply

  • P粉217784586

    P粉2177845862024-02-26 15:06:24

    Statement not allowed in SQL stored routines

    Allowed SQL syntax in prepared statements

    CREATE TRIGGER Not listed.


    Finally: Triggers cannot be created within stored procedures, functions, prepared statements, triggers, or event procedures.

    reply
    0
  • Cancelreply