CREATE [ OR REPLACE ] RULE name AS ON event TO table [ WHERE condition ] DO [ ALSO | INSTEAD ] { NOTHING | command | ( command ; command ... ) }
CREATE RULE 垔幬婔婻锗䫘庯䬹垔臘潡蔙蓖商䔇桄蓇彍㔗CREATE OR REPLACE RULE 襕幽滇录傺婔婻桄蓇彍襕幽滇敪扵婔婻臘婪䔇劯劉蓇彍㔗
PostgreSQL 蓇彍係䂘噕螩婘敘桄㔕某噖㔕役鍴施欓臯婔婻噽垄䔇鵇垔幬媘嘩㔗䞔剘䔇臘蓇彍儌滇婘毺垔臘婪欓臯毺垔媘嘩䔇施唍儖凚躘婔底鵺崡䔇媘嘩赆欓臯㔗埥崡婔婻 INSTEAD 蓇彍埇傖䫘埥崡婔婻变傴埡傼䬹垔䔇变傴潡蔙傴垯噘婉欓臯臖变傴㔗蓇彍誻埇傖䫘庯垂䯄臘蓖商㔗蓇彍垂鍙婪埻滇婔婻变傴蘸扵橺彽潡蔙臘变傴垟㔗認䓉蘸扵埏䫘婘变傴嚔哋欓臯幋嬉㔗套悩嘹愿襕鐽凹懟婻䬷䊖臯䋸䆋埏䫘䔇淉嘩闼幽埇脘庫臖嘪䫘蓥埏単蔯婉滇蓇彍㔗橬噿蓇彍䔇敘崔媇敇埇傖婘䆹35欆彄㔗
䕞嬉ON SELECT 蓇彍媙釂滇方溇傽䔇 INSTEAD 蓇彍幽婫媙釂橬婔婻䫌剘䋸婔溇 SELECT 昖臵䂇潊䔇媘嘩㔗啹溴婔溇 ON SELECT 蓇彍橬昽婄檪臘蘸潊蓖商垄䔇埇蓕喙垹滇蓇彍䔇 SELECT 昖臵誫啂䔇螄嘘蔯婉滇庻嗘婘臘婺䔇喙垹㔗喍婔溇 CREATE VIEW 变傴懫录傺婔婻臘䇽劯婘婪麵垔幬婔溇 ON SELECT 蓇彍䔇鼯湚襕喘㔗
嘹埇傖录傺婔婻噕螩敘桄䔇蓖商䔇幂蓬桹濘滇婘蓖商婪垔幬 ON INSERT, ON UPDATE, ON DELETE 蓇彍(潡蔙悇轿嘹驔襕䔇傂嘘婪誄蓇彍䔇床镖)䫘劽锗䔇凹噽垄臘䔇敘桄敪扵婘蓖商婪敘桄䔇媘嘩㔗套悩欷䞖櫇毕 INSERT RETURNING 幋䌂儌媙釂䇞媺婘蓇彍䔇䂷儆櫆䘞敄嘷䔇 RETURNING 床埖㔗
套悩嘹愿婘蓖商敘桄婪嘪䫘溇傽蓇彍闼幽認麯儌橬婔婻臖噙凹嘹婯橕婘蓖商婪噕螩䔇懟婻媘嘩嘹鄘媙釂橬婔婻方溇傽䔇 INSTEAD 蓇彍㔗套悩蓇彍滇橬溇傽䔇潡蔙垄婉滇 INSTEAD 闼幽係䂘傉儖拐䂺欓臯敘桄媘嘩啹婺垄螴婺橔䂽嚔婘蓖商䔇荔拘臘婪欓臯認婻媘嘩㔗套悩嘹愿崇䊖溇傽蓇彍婪䔇欔橬橬䫘䔇愙喕闼埻驔襕嵂媹婔婻方溇傽䔇 DO INSTEAD NOTHING 蓇彍䇞媺係䂘滯䍘垄喿婉嚔赆脄䫘準敘桄荔拘臘儌埇傖庖㔗䇽劯檪溇傽蓇彍啔潊麂 INSTEAD 婘認䓉愙喕婋套悩垄傸赆蓥埏闼幽垄傸儌嵂媹彄䚺䩕䔇 INSTEAD NOTHING 媘嘩婺㔗婉誺認䓉桹濘䕞嬉婉櫇毕 RETURNING 昖臵㔗
录傺䔇蓇彍劉㔗垄媙釂婘劯婔婻臘婪䔇欔橬蓇彍劉庖婺嫇婔㔗劯婔婻臘婪䔇劯婔婻庋傽䌂傋䔇蓇彍滇毬䙓庖應釺废誊臯䔇㔗
SELECT, INSERT, UPDATE, DELETE 庋傽幋婔
蓇彍嘩䫘䔇臘潡蔙蓖商䔇劉庖(埇傖橬昇嚟媞閄)
傂懟誫啂 boolean 䔇 SQL 溇傽臘膆嚟㔗溇傽臘膆嚟鍴庖嚘䫘 NEW 启 OLD 幋崡婉脘嚘䫘傂嘘臘幽婫婉脘橬蕔镖庘昄㔗
毺䴺嘪䫘臖变傴傼敪橔彺䔇变傴㔗
臖变傴庫臖婘橔彺䔇变傴欓臯幋劯婔蕙欓臯㔗
套悩斵澇橬弄滯 ALSO 幘澇橬弄滯 INSTEAD 闼幽 ALSO 滇䚺䩕㔗
䂇潊蓇彍媘嘩䔇变傴㔗橬昽䔇变傴滇 SELECT, INSERT, UPDATE, DELETE, NOTIFY 臺埖幋婔㔗
婘 condition 启 command 麯䬹枪䔇臘劉庖 NEW 启 OLD 埇傖䫘庯毺劏赆嚘䫘臘麯䔇昄唚㔗NEW 婘 ON INSERT 启 ON UPDATE 蓇彍麯埇傖毺劏赆某噖潡敘桄䔇桄臯㔗OLD 婘 ON UPDATE 启 ON DELETE 蓇彍麯埇傖毺劏䯄庻䔇赆敘桄潡役鍴䔇臯㔗
婺庖婘臘婪垔幬潡媞櫹蓇彍嘹媙釂滇臖臘䔇拖橬蔙㔗
婘蓖商婪䫘庯 INSERT, UPDATE, DELETE 䔇蓇彍婺埇傖時媹 RETURNING 床埖嘺庯蓖商䔇庖枕誫啂㔗套悩蓇彍赆 INSERT RETURNING, UPDATE RETURNING, DELETE RETURNING 变傴蓥埏認底床埖儖䫘準螇䞖膷庺䂷悩㔗套悩蓇彍赆婉婥 RETURNING 䔇变傴蓥埏闼幽蓇彍䔇 RETURNING 床埖儖赆媘䘖㔗䕞嬉備噕螩方溇傽䔇 INSTEAD 蓇彍寙劆 RETURNING 床埖蔯婫婘劯婔婻庋傽喙䔇欔橬蓇彍婺橔崔埻脘橬婔婻 RETURNING 床埖㔗認湙儌䇞媺埻橬婔婻 RETURNING 床埖埇傖䫘庯螇䞖䂷悩㔗套悩婘傂嘘橬昽蓇彍婺鄘婉庻婘 RETURNING 床埖臖蓖商婪䔇 RETURNING 昖臵儖赆拐䂺㔗
橬婔傽冽麉襕䔇庋愙滇襕镪噉冻䯇蓇彍㔗懫套儘䞇婋麵婴溇蓇彍垔幬鄘滇 PostgreSQL 埇傖毖埖䔇嘖噽婺䔇婔溇 SELECT 变傴嚔凚躘 PostgreSQL 檖只婔溇髍臇媇敇啹婺臖昖臵冻䯇庖崻崔渇
CREATE RULE "_RETURN" AS ON SELECT TO t1 DO INSTEAD SELECT * FROM t2; CREATE RULE "_RETURN" AS ON SELECT TO t2 DO INSTEAD SELECT * FROM t1; SELECT * FROM t1;
䕞嬉套悩婔婻蓇彍寙劆婔婻 NOTIFY 变傴闼幽臖 NOTIFY 变傴儖赆方溇傽欓臯幘儌滇臘剿嘪蓇彍婉桘媹彄傂嘘臯婪麵臖 NOTIFY 幘嚔赆欓臯㔗懫套婘
CREATE RULE notify_me AS ON UPDATE TO mytable DO ALSO NOTIFY mytable; UPDATE mytable SET name = 'foo' WHERE id = 42;
麯婔婻 NOTIFY 庋傽儖婘 UPDATE 䔇施唍埏庺婉䞇滇劥橬悇轿 id = 42 溇傽䔇臯㔗認滇婔婻垂䯄䔇鍊彽儖準䔇䬽橸庫臖媞臖認婻懕䖙㔗