触发器
触发器是(trigger)是个特殊的存储你过程,它的执行不是由程序调用,也不是手动启动,而是由事件来触发,比如当对一个表进行操作(INSERT,DELETE,UPDATE)时就会激活它执行。触发器经常 用来加强数据的完整性约束和业务规则等。触发器可以从DBA_TRIGGERS, USER_TRIGGES数据字典中查到。
触发器语法
CREATE TRIGGER
trigger_name
TRIGGER_TIME[AFTER,BEFORE]
TRIGGER_EVENT[UPDATE,INSERT,DELETE]
ON tbl_name
FOR EACH ROW trigger_stmt
触发器实现两表同步
#同步插入
DELIMITER $$ #修改定界符
DROP TRIGGER IF EXISTS sync_apps_insert$$
CREATE TRIGGER sync_apps_insert AFTER INSERT ON rht_train.rht_apps FOR EACH ROW
BEGIN
INSERT INTO rht_idc.rhi_apps
(id, appid, appname, isreward, adesc, adetail, price, downcount, sortid, iftj, flag, apptype, appcol, imgurl, ver, vernum, iconurl, filesize, lang, appurl, package, ctime, utime, stars, signature, unconfirm, develop, typeinfo) VALUES
(NEW.id, NEW.appid, NEW.appname, NEW.isreward, NEW.adesc, NEW.adetail, NEW.price, NEW.downcount, NEW.sortid, NEW.iftj, NEW.flag, NEW.apptype, NEW.appcol, NEW.imgurl, NEW.ver, NEW.vernum, NEW.iconurl, NEW.filesize, NEW.lang, NEW.appurl, NEW.package, NEW.ctime, NEW.utime, NEW.stars, NEW.signature, NEW.unconfirm, NEW.develop, NEW.typeinfo);
END $$
DELIMITER ; #还原定界符
#同步删除
DELIMITER $$ #修改定界符
DROP TRIGGER IF EXISTS sync_apps_delete$$
CREATE TRIGGER sync_apps_delete AFTER DELETE ON rht_train.rht_apps FOR EACH ROW
BEGIN
DELETE FROM rht_idc.rhi_apps WHERE rht_idc.rhi_apps.id=OLD.id;
END $$
DELIMITER ; #还原定界符
#同步更新
DELIMITER $$ #修改定界符
DROP TRIGGER IF EXISTS sync_apps_update$$
CREATE TRIGGER sync_apps_update AFTER UPDATE ON rht_train.rht_apps FOR EACH ROW
BEGIN
UPDATE `rht_idc`.`rhi_apps` SET `id`=NEW.id, `appid`=NEW.appid, `appname`=NEW.appname,
`isreward`=NEW.isreward, `adesc`=NEW.adesc, `adetail`=NEW.adetail, `price`=NEW.price, `downcount`=NEW.downcount,
`sortid`=NEW.sortid, `iftj`=NEW.iftj, `flag`=NEW.flag, `apptype`=NEW.apptype, `appcol`=NEW.appcol, `imgurl`=NEW.imgurl,
`ver`=NEW.ver, `vernum`=NEW.vernum, `iconurl`=NEW.iconurl, `filesize`=NEW.filesize, `lang`=NEW.lang, `appurl`=NEW.appurl,
`package`=NEW.package, `ctime`=NEW.ctime, `utime`=NEW.utime, `stars`=NEW.stars, `signature`=NEW.signature,
`unconfirm`=NEW.unconfirm, `develop`=NEW.develop, `typeinfo`=NEW.typeinfo WHERE (rht_idc.rhi_apps.id=OLD.id);
END $$
DELIMITER ; #还原定界符
如果执行返回
Trigger in wrong schema
请检查use datebases 是否是rht_train。触发器是建立在此库上的表,应当选择此库才能正常建立。