您的位置:首页 > 数据库

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

2013-12-12 00:00 323 查看
摘要: postgres 没有oracle的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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  postgresql merge trigger