postgres 模拟merge 插入或者对已存在进行更新

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
相关文章
相关标签/搜索