MySQL触发器防止插入

时间:2018-11-09 15:20:12

标签: mysql

CREATE TABLE IF NOT EXISTS types (
  id INT(4) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(80),
  INDEX(name)
) engine=InnoDB;

CREATE TABLE IF NOT EXISTS owners (
  id INT(4) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  first_name VARCHAR(30),
  last_name VARCHAR(30),
  address VARCHAR(255),
  city VARCHAR(80),
  telephone VARCHAR(20),
wallet DECIMAL(),
  INDEX(last_name)
) engine=InnoDB;

CREATE TABLE IF NOT EXISTS pets (
  id INT(4) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(30),
  birth_date DATE,
  type_id INT(4) UNSIGNED NOT NULL,
  owner_id INT(4) UNSIGNED NOT NULL,
  INDEX(name),
  FOREIGN KEY (owner_id) REFERENCES owners(id),
  FOREIGN KEY (type_id) REFERENCES types(id)
) engine=InnoDB;

CREATE TABLE IF NOT EXISTS visits (
  id INT(4) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  pet_id INT(4) UNSIGNED NOT NULL,
  visit_date DATE,
  description VARCHAR(255),
  FOREIGN KEY (pet_id) REFERENCES pets(id)
) engine=InnoDB;

在此之前,我仅使用mssql,并且可以在触发器内部使用回滚 但是你不能那样做。我想编写回滚触发器,或者不允许为负债1000的宠物所有者设置新的访问次数

我什至试图编写这样一个简单的触发器,但是它也不起作用

CREATE TRIGGER wallet_check before INSERT ON visits 
FOR EACH ROW
    BEGIN

    IF(NEW.pet_id <3) then 
  INSERT INTO visits(id,visit_date,description,pet_id,vet_id)
VALUES (NEW.id, NEW.visit_date, NEW.description,NEW.pet_id,NEW.vet_id);


END IF;
END

我读到在mysql中您会在这种情况下使用事务,但是我不知道该怎么写。

1 个答案:

答案 0 :(得分:0)

您可以使用SET SIGNALSTATEBEFORE INSERT触发器中引发异常。这将停止执行,并且INSERT不会发生。

DELIMITER $$
CREATE TRIGGER wallet_check BEFORE INSERT ON visits 
FOR EACH ROW
    BEGIN

    IF(NEW.pet_id >= 3) THEN -- throw exception 
      SIGNAL SQLSTATE '45000' SET message_text = 'pet_id cannot be more than 3';
    END IF;
END $$
DELIMITER ;