MySQL trigger if condition exists

后端 未结 2 1724
隐瞒了意图╮
隐瞒了意图╮ 2020-12-14 20:40

I\'m trying to write an update trigger that will only update a password when a new password is set in the update statement but I\'m having a terrible time trying to nail dow

相关标签:
2条回答
  • 2020-12-14 21:16

    I think you mean to update it back to the OLD password, when the NEW one is not supplied.

    DROP TRIGGER IF EXISTS upd_user;
    
    DELIMITER $$
    
        CREATE TRIGGER upd_user BEFORE UPDATE ON `user`
        FOR EACH ROW BEGIN
          IF (NEW.password IS NULL OR NEW.password = '') THEN
                SET NEW.password = OLD.password;
          ELSE
                SET NEW.password = Password(NEW.Password);
          END IF;
        END$$
    
    DELIMITER ;
    

    However, this means a user can never blank out a password.


    If the password field (already encrypted) is being sent back in the update to mySQL, then it will not be null or blank, and MySQL will attempt to redo the Password() function on it. To detect this, use this code instead

    DELIMITER $$
    
        CREATE TRIGGER upd_user BEFORE UPDATE ON `user`
        FOR EACH ROW BEGIN
          IF (NEW.password IS NULL OR NEW.password = '' OR NEW.password = OLD.password) THEN
                SET NEW.password = OLD.password;
          ELSE
                SET NEW.password = Password(NEW.Password);
          END IF;
        END$$
    
    DELIMITER ;
    
    0 讨论(0)
  • 2020-12-14 21:22

    Try to do...

     DELIMITER $$
            CREATE TRIGGER aumentarsalario 
            BEFORE INSERT 
            ON empregados
            FOR EACH ROW
            BEGIN
              if (NEW.SALARIO < 900) THEN 
                 set NEW.SALARIO = NEW.SALARIO + (NEW.SALARIO * 0.1);
              END IF;
            END $$
      DELIMITER ;
    
    0 讨论(0)
提交回复
热议问题