MySQL trigger if condition exists
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 down the syntax. This should be a no-brainer but I'm just not finding the solution.
Here's my code:
CREATE TRIGGER upd_user BEFORE UPDATE ON `user`
FOR开发者_StackOverflow社区 EACH ROW BEGIN
IF (NEW.password <> '') THEN
SET NEW.password = PASSWORD(NEW.password);
END IF;
END;
I've tried:
IF (NEW.password <> NULL) THEN
IF (NEW.password) THEN
IF NEW.password <> NULL THEN
IF (NEW.password > 0) THEN
IF (NEW.password != NULL) THEN
And I'm sure many other combinations but it's just not working. Does anyone have any insight?
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 ;
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 ;
精彩评论