1

我正在尝试在 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

然而,我是触发器的新手,并且一直在尝试一件事或三件事,但似乎我确实需要一些帮助,我希望我把问题说清楚了,非常感谢。

4

1 回答 1

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 ;
    
于 2012-08-26T18:08:14.940 回答