如何创建MySQL触发器

时间:2016-06-29 10:53:29

标签: mysql triggers

我的表users包含两个字段id(数字)和email(带有完整的电子邮件地址)如何添加触发器,这可能会阻止添加新的email记录特定域名,例如:*@somedomain.com

2 个答案:

答案 0 :(得分:1)

触发器看起来像这样:

DELIMITER $$

CREATE TRIGGER USER_INSERT BEFORE INSERT ON USER
    FOR EACH ROW
BEGIN
  IF new.email like '%@somedomain.com' THEN
    SIGNAL sqlstate '99999'
        SET message_text = 'Invalid domain';
  END IF;
END$$ 

DELIMITER ;

答案 1 :(得分:0)

请尝试:

DELIMITER $$

CREATE TRIGGER example_before_insert_reject_domains
     BEFORE INSERT ON example_tbl FOR EACH ROW
     BEGIN
          IF NEW.email LIKE '%@somedomain.com'
          THEN
               SIGNAL SQLSTATE '45000'
                    SET MESSAGE_TEXT = 'Cannot add or update row: invalid domain for email';
          END IF;
     END;
$$