删除之前的mysql触发器插入记录,如果删除或更新

时间:2012-08-26 17:12:57

标签: mysql triggers

我正在尝试在mysql表上写一个删除前的触发器,这是我正在努力做的事情;我需要一个特定的记录,总是在表中,所以说例如删除或更新记录,触发器只需重新​​插入初始记录。

EXAMPLE
Tablename: Users
Table Columns(3):ID,Username,Password
and I am trying to keep the following record from being deleted(Initial Record)
Username=Dames, Password=Password

然而我是触发器的新手并且已经尝试了一件事或者3但是我真的需要一些帮助,我希望我能清楚地提出这个问题,并且非常感谢。

1 个答案:

答案 0 :(得分:3)

  1. 如果您很乐意在触发器中硬编码您希望保留的记录的详细信息,那么您可以执行以下操作:

    DELIMITER ;;
    
    CREATE TRIGGER foo_upd BEFORE UPDATE ON Users FOR EACH ROW
    IF OLD.Username <=> 'Dames' AND OLD.Password <=> 'Password' THEN
      INSERT INTO Users (Username, Password) VALUES ('Dames', 'Password');
    END IF ;;
    
    CREATE TRIGGER foo_del BEFORE DELETE ON Users FOR EACH ROW
    IF OLD.Username <=> 'Dames' AND OLD.Password <=> 'Password' THEN
      INSERT INTO Users (Username, Password) VALUES ('Dames', 'Password');
    END IF ;;
    
    DELIMITER ;
    
  2. 否则,我建议在Users表中添加一个额外的布尔列 - 例如。 locked

    ALTER TABLE Users ADD COLUMN locked BOOLEAN NOT NULL DEFAULT FALSE;
    

    然后在您希望保留的记录上将该列的值设置为TRUE

    UPDATE Users SET locked = TRUE
    WHERE  Username = 'Dames' AND Password = 'Password';
    

    然后按以下行创建触发器:

    DELIMITER ;;
    
    CREATE TRIGGER foo_upd BEFORE UPDATE ON Users FOR EACH ROW
    IF OLD.locked THEN
      INSERT INTO Users (Username, Password) VALUES (OLD.Username, OLD.Password);
    END IF ;;
    
    CREATE TRIGGER foo_del BEFORE DELETE ON Users FOR EACH ROW
    IF OLD.locked THEN
      INSERT INTO Users (Username, Password) VALUES (OLD.Username, OLD.Password);
    END IF ;;
    
    DELIMITER ;