gpt4 book ai didi

MYSQL 触发器中的多个事件

转载 作者:行者123 更新时间:2023-11-29 23:30:31 24 4
gpt4 key购买 nike

如何为这两个 CHECK 约束创建触发器

create table section ( course_id varchar(8), 
sec_id varchar(8),
semester varchar(6)
check (semester in ('Fall', 'Winter', 'Spring', 'Summer')),
year numeric(4,0)
check (year > 1701 and year < 2100),
building varchar(15),
room_number varchar(7),
time_slot_id varchar(4),
primary key (course_id, sec_id, semester, year),
foreign key (course_id) references course on delete cascade,
foreign key (building, room_number) references classroom on delete set null);

================================================== =========================

除了解决方案。

最佳答案

乌扎尔,

正如文章“Validating data using a TRIGGER”中所述,您应该使用 BEFORE INSERT 触发器来验证您的数据,如下所示:

-- validate semester
CREATE TRIGGER `semester_validate_semester_insert`
BEFORE INSERT
ON `section`
FOR EACH ROW
BEGIN
IF NEW.`semester` NOT IN ('Fall', 'Winter', 'Spring', 'Summer') THEN
SIGNAL SQLSTATE VALUE '45000'
SET MESSAGE_TEXT = '[table:section] - `semester` column is not valid';
END IF;
END;

-- validate year
CREATE TRIGGER `semester_validate_year_insert`
BEFORE INSERT
ON `section`
FOR EACH ROW
BEGIN
IF NEW.`year` <= 1701 OR NEW.`year` >= 2100) THEN
SIGNAL SQLSTATE VALUE '45000'
SET MESSAGE_TEXT = '[table:section] - `YEAR` column is not valid';
END IF;
END;

如果您有任何疑问,请告诉我!

关于MYSQL 触发器中的多个事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26621475/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com