MySQL triggers cannot update rows in same table the trigger is assigned to. Suggested workaround?

前端 未结 5 1867
鱼传尺愫
鱼传尺愫 2020-11-28 15:11

MySQL doesn\'t currently support updating rows in the same table the trigger is assigned to since the call could become recursive. Does anyone have suggestions on a good wor

相关标签:
5条回答
  • 2020-11-28 15:56

    You can actually up the rows in the same table as the trigger. The thread you linked to even has the solution.

    For example:

    TestTable ( id / lastmodified / random )
    
    create trigger insert_lastmod
    before insert on TestTable
    for each row
    set NEW.lastmodified = NOW();
    
    insert into TestTable ( `random` ) values ( 'Random' );
    
    select * from TestTable;
    +----+---------------------+---------------------+
    | id | lastmodified        | random              |
    +----+---------------------+---------------------+
    |  1 | 2010-12-22 14:15:23 | Random              |
    +----+---------------------+---------------------+
    
    0 讨论(0)
  • 2020-11-28 16:00

    This worked for me :D

    On Before / Update.

    BEGIN
     SET NEW.DateTimeUpdated = NOW();
    END
    
    0 讨论(0)
  • 2020-11-28 16:10

    I suppose you could call the stored proc in your trigger. HOwever, if you want to update some fields in the same records that you are changing (such as an updatedby or lastupdated column) then you can do this in a beofre trigger according to the refernce manual. http://dev.mysql.com/doc/refman/5.0/en/trigger-syntax.html

    This is a common operation for triggers and I find it difficult to believe it isn't supported.

    0 讨论(0)
  • 2020-11-28 16:13

    You can actually do that The below is an example for same

    DELIMITER $$
    create trigger test2 
    before insert on ptrt 
    for each row 
    begin 
    if NEW.DType = "A" then 
    set NEW.PA = 500; 
    
    elseif NEW.DType = "B" then 
    set NEW.PA = 1000; 
    
    else 
    set NEW.PA = 0; 
    END IF; 
    END;$$
    
    DELIMITER;
    
    0 讨论(0)
  • 2020-11-28 16:14

    If you want to update column that you don't read in trigger function, then as a workaround, you could put that column into separate table.

    0 讨论(0)
提交回复
热议问题