我想防止Check条件不成立时插入MySQL数据库。例如,在下面的MySQL查询中,我添加了一个检查约束,即Gender只能是“ M”或“ F”,但仍然可以插入“ T”。
CREATE TABLE STUDENT
(S_FIRST VARCHAR(10) NOT NULL,
S_LAST VARCHAR(10) NOT NULL,
GENDER VARCHAR(1) NOT NULL CHECK (GENDER="M" OR GENDER="F"),
S_EMAIL VARCHAR(50) NOT NULL CHECK (S_EMAIL="%@%.COM"),
S_PHONE VARCHAR(10) NOT NULL CHECK (S_PHONE<9999999999),
DATE_OF_BIRTH DATE NOT NULL,
S_ID INT(3) PRIMARY KEY AUTO_INCREMENT);
INSERT INTO STUDENT VALUE("ABNISH","NIRAJ","T","ABNISHNIRAJ10@GMAIL.COM","7062123799",'1996-10-19',NULL);
-- the Second query should not work since the Gender is "T"
答案 0 :(得分:0)
检查约束在MySql版本8中引入。
替代方法是使用触发器
DELIMITER $$
CREATE TRIGGER `test_before_insert` BEFORE INSERT ON `Test`
FOR EACH ROW
BEGIN
IF NEW.GENDER NOT IN ('F', 'M') THEN
SIGNAL SQLSTATE '12345'
SET MESSAGE_TEXT := 'check constraint on GENDER failed';
END IF;
END$$
DELIMITER ;