1. 程式人生 > >觸發器實現源表操作(增,刪,改)自動補錄操作日誌

觸發器實現源表操作(增,刪,改)自動補錄操作日誌

not in then use lec varchar prim datetime int sele

1:源表數據修改時將修改的數據插入臨時表,標記字段為修改
2:源表數據刪除時將刪除數據插入臨時表,編輯字段為刪除
3:源表數據新增時將新增數據插入臨時表,標記字段為新增 一:定義臨時表字段
1:查看源數據testb表
-------------如何修改mysql已經建好表的編碼------------------------------
ALTER TABLE 表名 DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci; 2:創建第一個觸發器---插入觸發器
create trigger tri_userC_insert AFTER insert
on `usera` FOR EACH ROW
begin
insert into userc(idC,nameC,ageC,flogS,flog_time) select id,name,age,‘插入‘,now() from usera where id not in (select idC from `userc`);
end 3:創建第二個觸發器---更新觸發器
create trigger tri_userC AFTER update
on `usera` FOR EACH ROW
begin
set @point=(select name from `usera` where id = OLD.id );
set @point02=(select age from `usera` where id = OLD.id );
if @point != old.name then
update `userc` set nameC=@point where idC=OLD.id;
update `userc` set flogS=‘更新‘ where idC=OLD.id;
update `userc` set flog_time=now() where idC=OLD.id;
end if;
if @point02 != old.age then
update `userc` set ageC=@point02 where idC=OLD.id;
update `userc` set flogS=‘更新‘ where idC=OLD.id;
update `userc` set flog_time=now() where idC=OLD.id;
end if;
end
4:創建第三個觸發器---刪除觸發器
create trigger tri_userC_delete AFTER delete
on `usera` FOR EACH ROW
begin
update userc set flogs = ‘刪除‘ where idC not in (select id from `usera`);
update userc set flog_time = now() where idC not in (select id from `usera`);
end
5:建表語句(A表)
CREATE TABLE `usera` (
`id` int(10) NOT NULL,
`name` varchar(50) DEFAULT NULL,
`age` int(3) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8; 6:建表語句(C表)
CREATE TABLE `userc` (
`idC` int(255) NOT NULL,
`nameC` varchar(255) DEFAULT NULL,
`ageC` int(255) DEFAULT NULL,
`flogs` varchar(255) DEFAULT NULL,
`flog_time` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

觸發器實現源表操作(增,刪,改)自動補錄操作日誌