练习题目
创建职工表以及职工工资表
职工表字段:工号,姓名,性别,年龄
工资表字段:编号自增,职工工号,基础工资10000
通过触发器实现:
对职工进行添加时:
工资表中也要体现当前职工的信息
对职工进行修改时:
工资表中也要一并修改当前职工的信息
对职工进行解聘时:
工资表中也要一并删除当前员工的工资信息
解题思路:
1、创建库
2、创建职工表和工资表
3、创建触发器分别实现功能
步骤如下:
1、创建库
CREATE DATABASE Work_db;
2、创建表
CREATE TABLE Worker(
WorkerID INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
WorkerName VARCHAR(20),
WorkerSex ENUM ('m' , 'w'),
Age INT
);
CREATE TABLE Wages(
ID INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
WorkerID INT NOT NULL,
Salary DOUBLE(10,2)
);
3、创建触发器实现对职工添加工资表也有体现
CREATE TRIGGER Worker_insert_trigger
AFTER INSERT ON Worker
FOR EACH ROW
BEGIN
INSERT INTO Wages VALUES (NULL,new.WorkerID,10000);
END;
INSERT INTO Worker VALUES(1,'张三','m',20);
INSERT INTO Worker VALUES(2,'李四','m',30);
INSERT INTO Worker VALUES(3,'王五','m',40);
4、创建触发器实现,对职工进行修改时,工资表也有修改
CREATE TRIGGER Worker_update_trigger
AFTER UPDATE ON Worker
FOR EACH ROW
BEGIN
UPDATE Wages SET WorkerID = new.WorkerID WHERE WorkerID = old.WorkerID;
END;
修改内容
UPDATE Worker SET WorkerID = '12' WHERE WorkerID ='1';
测试
5、创建触发器,实现对职工进行解聘时,工资表也有相应的变化
CREATE TRIGGER Worker_delete_trigger
AFTER DELETE ON Worker
FOR EACH ROW
BEGIN
DELETE FROM Wages WHERE WorkerID = old.WorkerID;
END;
测试:
删除数据
DELETE FROM Wages WHERE WorkerID = '12';