引发错误在 MySQL 触发器中不起作用
Posted
技术标签:
【中文标题】引发错误在 MySQL 触发器中不起作用【英文标题】:Raising Error not working in MySQL trigger 【发布时间】:2021-08-04 23:11:28 【问题描述】:如果一个人的姓氏不是全大写或者他们的名字的第一个字母不是大写,我试图在我的触发器中引发一个错误。但是,如果遇到这些情况,我的代码似乎不会发出警报。有人可以向我解释一下我该怎么做吗?
这是我的桌子:
DROP TABLE IF EXISTS people;
CREATE TABLE IF NOT EXISTS people (
Id_People smallint(5) unsigned NOT NULL AUTO_INCREMENT,
Firstname varchar(20) NOT NULL,
Lastname varchar(20) NOT NULL,
Birth DATE,
PRIMARY KEY (Id_People)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1002 ;DROP TRIGGER IF EXISTS insert_people;
这是我的触发器
DROP TRIGGER IF EXISTS insert_people;
DELIMITER $$
CREATE TRIGGER insert_people BEFORE INSERT ON people
FOR EACH ROW BEGIN
IF NOT (NEW.Lastname like UCASE ) THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'the lastname must be in full caps ';
ELSE IF
NOT (NEW.Firstname like ucfirst ) THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'the first letter of the firstname must be in caps';
END IF;
END IF;
END$$
【问题讨论】:
什么是ucase和ucfirst? ucase 是大写字母,ucfirst 是大写字母中的第一个字母 这些是在哪里定义的? 【参考方案1】:你找到的代码不正确。
请在触发代码中添加DELIMITER
,因为在示例站点中不是必需的
DROP TABLE IF EXISTS people; CREATE TABLE IF NOT EXISTS people ( Id_People smallint(5) unsigned NOT NULL AUTO_INCREMENT, Firstname varchar(20) NOT NULL, Lastname varchar(20) NOT NULL, Birth DATE, PRIMARY KEY (Id_People) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1002 ;DROP TRIGGER IF EXISTS insert_people;
CREATE TRIGGER insert_people BEFORE INSERT ON people FOR EACH ROW BEGIN IF NOT (NEW.Lastname=BINARY UPPER(NEW.Lastname)) THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'the lastname must be in full caps '; ELSE IF NOT (ASCII(NEW.Firstname) BETWEEN 65 AND 90 ) THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'the first letter of the firstname must be in caps'; END IF; END IF; END
姓氏必须大写INSERT INTO people VALUES (NULL,'Hallo','Kitty','1980-01-01')
名字的第一个字母必须大写INSERT INTO people VALUES (NULL,'hallo','KITTY','1980-01-01')
db小提琴here
【讨论】:
以上是关于引发错误在 MySQL 触发器中不起作用的主要内容,如果未能解决你的问题,请参考以下文章