skip to Main Content

I want to make the code that if any of new column’s value is null
change that one to the value of row before with trigger event

CREATE TRIGGER updateField BEFORE INSERT ON message
       FOR EACH ROW 
 
       IF (NEW.COLUMN IS NULL) then
       set NEW.COLUMN = SELECT THE_COLUMN FROM Table ORDER BY ID DESC LIMIT 1;
       
       END IF

2

Answers


  1. If you use a compound statement like IF/THEN/END IF, you must put the body of the trigger in a BEGIN..END block.

    ...
    
    FOR EACH ROW BEGIN
    
       IF (NEW.COLUMN IS NULL) THEN
         SET NEW.COLUMN = (SELECT THE_COLUMN FROM Table ORDER BY ID DESC LIMIT 1);
       
       END IF;
    END
    
    Login or Signup to reply.
  2. You must also have a BEGIN and END
    if you have more than a code line

    DELIMITER $$
    CREATE TRIGGER updateField BEFORE INSERT ON message
           FOR EACH ROW 
             BEGIN
                   IF (NEW.COLUMN IS NULL) then
                        set NEW.COLUMN = (SELECT THE_COLUMN FROM Table1 ORDER BY ID DESC LIMIT 1);       
                   END IF;
            END$$
    DELIMITER ;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search