QQ羣裏這幾天一直有人要作相似merge或者replace的操做,嚷嚷表字段多 用function進行insert or update寫起來麻煩。OK,下面貼一個 觸發器進行replace的demo 寫個觸發器 插入以前執行觸發器 -- 建立一個測試表 create table test(id int primary key , name varchar(50)); -- 觸發器 插入前ID若是已經存在則替換name的值 CREATE OR REPLACE function _replace() RETURNS TRIGGER AS $INSERT$ declare _has int ; BEGIN -- 判斷ID 是否已經存在 select 1 from test where id = NEW.id into _has; raise notice 'ddd:%' , _has; if _has > 0 then -- 存在 則更新 而後返回null update test set name = NEW.name where id = NEW.id; RETURN null; end if; -- 不存在 則返回 讓執行該作的插入操做 return NEW; END; $INSERT$ LANGUAGE PLPGSQL; -- 給表加上觸發器 只針對insert CREATE TRIGGER tbefore BEFORE INSERT ON test FOR EACH ROW EXECUTE PROCEDURE _replace(); -- 插入兩個值 insert into test(id , name) values(1,'1'); insert into test(id , name) values(1,'6'); --查詢 select * from test; 結果: pumpkin=> select * from test; id | name ----+------ 1 | 6 (1 行記錄) 時間:1.474 ms