1.建person表
CREATE TABLE `person` (
`id` int(11) DEFAULT NULL,
`name` varchar(256) DEFAULT NULL,
`sex` char(16) DEFAULT NULL
)
建person_ex
CREATE TABLE `person_ex` (
`id` int(11) DEFAULT NULL,
`name` varchar(256) DEFAULT NULL,
`sex` char(16) DEFAULT NULL
)
2.实现的目标当person新增一条记录,更新一条记录或者删除一条记录,person_ex中sex字段为M的记录跟着改变
sql代码如下:
创建插入触发器
create trigger person_trigger AFTER insert on person for each row
begin set @x = "hello trigger";
IF new.sex = ‘M‘
THEN
INSERT INTO person_ex(id,name,sex) VALUES (New.id,new.`name`,new.sex);
END IF;
end;
创建更新触发器:
create trigger person_trigger_update AFTER UPDATE on person for each row
begin set @x = "trigger UPDATE";
IF new.sex = ‘M‘
THEN
DELETE from person_ex where person_ex.id = new.id;
INSERT into person_ex SELECT * from person where person.id = new.id;
END IF;
end;
创建删除触发器:
create trigger person_trigger_delete AFTER DELETE on person for each row
begin set @x = "trigger DELETE";
DELETE FROM person_ex where person_ex.id = old.id;
end;
3.测试SQL代码:
INSERT into person (id,name,sex) VALUES (1,‘chigo‘,‘M‘)
INSERT into person (id,name,sex) VALUES (2,‘Tony‘,‘F‘)
update person set name = ‘vara‘ , sex = ‘F‘ where id = 1
update person set name = ‘Tony‘ , sex = ‘M‘ where id = 1
update person set name = ‘vara‘ , sex = ‘M‘ where id = 1
DELETE from person where id = 1
INSERT into person_ex SELECT * from person where person.id = 1
update person set name = ‘vara‘ , sex = ‘F‘ where id = 1