MySQL高级语法:触发器练习
1 例1
创建一个触发器,当在供应商表S中添加一个供应商信息的时候,如果城市不为‘杭州’,‘北京’,‘天津’,‘上海’,则取消插入操作
DELIMITER //
CREATE TRIGGER before_insert_supplier
BEFORE INSERT ON S
FOR EACH ROW
BEGIN
-- 检查城市是否为允许的城市
IF NEW.city NOT IN ('杭州', '北京', '天津', '上海') THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = '城市不在允许的列表中,取消插入操作';
END IF;
END //
DELIMITER ;
2 例2
创建一个触发器,当在工程项目表J中删除一条记录时,在SPJ中也删除该项目的供货信息
DELIMITER //
CREATE TRIGGER after_delete_project
AFTER DELETE ON J
FOR EACH ROW
BEGIN
-- 删除相关的供货信息
DELETE FROM SPJ
WHERE project_id = OLD.project_id;
END //
DELIMITER ;
3 例3
创建一个触发器,当在零件表P中修改零件编号的时候,在SPJ中也修改该零件的编号
DELIMITER //
CREATE TRIGGER after_update_part_number
AFTER UPDATE ON P
FOR EACH ROW
BEGIN
-- 检查是否是零件编号的变化
IF OLD.part_number != NEW.part_number THEN
-- 更新 SPJ 表中的零件编号
UPDATE SPJ
SET part_number = NEW.part_number
WHERE part_number = OLD.part_number;
END IF;
END //
DELIMITER ;
4 例4
创建一张Slog表,用于记录供应商表的操作情况
Create table slog(
log_id int(11) AUTO_INCREMENT, -- 操作日志id
operType varchar(20), -- 操作类型:insert(插入)、delete(删除)、update(更新)
operTime datetime, -- 操作时间
operUser varchar(50), -- 执行操作的用户名称
sno varchar(20),
primary key (log_id)
)
再创建三个触发器,分别在新增,修改和删除后,将操作保存到操作日志表中
DELIMITER //
CREATE TRIGGER after_insert_supplier
AFTER INSERT ON S
FOR EACH ROW
BEGIN
INSERT INTO slog (operType, operTime, operUser, sno)
VALUES ('insert', NOW(), USER(), NEW.sno);
END //
DELIMITER ;
DELIMITER //
CREATE TRIGGER after_update_supplier
AFTER UPDATE ON S
FOR EACH ROW
BEGIN
INSERT INTO slog (operType, operTime, operUser, sno)
VALUES ('update', NOW(), USER(), NEW.sno);
END //
DELIMITER ;
DELIMITER //
CREATE TRIGGER after_delete_supplier
AFTER DELETE ON S
FOR EACH ROW
BEGIN
INSERT INTO slog (operType, operTime, operUser, sno)
VALUES ('delete', NOW(), USER(), OLD.sno);
END //
DELIMITER ;