SQL触发器练习

创建职工表以及职工工资表
职工表字段:工号,姓名,性别,年龄
工资表字段:编号自增,职工工号,基础工资10000
通过触发器实现:
对职工进行添加时 工资表中也要体现当前职工的信息
对职工进行修改时 工资表中也要一并修改当前职工的信息
对职工进行解聘时 工资表中也要一并删除当前员工的工资信息

建立职工表 职工工资表
#职工表
CREATE TABLE worker (
	id INT AUTO_INCREMENT PRIMARY KEY NOT NULL,
	name VARCHAR(40) NOT NULL,
	sex VARCHAR(4) NOT NULL,
	age INT NOT NULL
);

#职工工资表
CREATE TABLE wage (
	id INT AUTO_INCREMENT PRIMARY KEY NOT NULL,
	name VARCHAR(20) NOT NULL,
	salary DOUBLE(10,2)
);

建立添加触发器
CREATE TRIGGER worker_insert_trigger
	AFTER INSERT ON worker
	FOR EACH ROW
	BEGIN
		INSERT INTO wage VALUES (NULL,new.name,10000);
	END;

建立修改触发器

CREATE TRIGGER worker_update_trigger
	AFTER UPDATE ON worker
	FOR EACH ROW
	BEGIN
		UPDATE wage SET name = new.name WHERE name = old.name;
	END;
建立删除触发器
CREATE TRIGGER worker_delete_trigger
	AFTER DELETE ON worker
	FOR EACH ROW
	BEGIN
		DELETE FROM wage WHERE name = old.name;
	END;

你可能感兴趣的:(sql,数据库)