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
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
相关文章推荐
- mysql触发器
- 用一整天的时间安装postgreSQL NTFS权限
- PostgreSQL8.3.3安装方法第1/2页
- PostgreSQL中的OID和XID 说明
- PostgreSQL 创建表分区
- PostgreSQL 安装和简单使用第1/2页
- Windows PostgreSQL 安装图文教程
- Windows下PostgreSQL安装图解
- 将MySQL数据库移植为PostgreSQL
- C#访问PostGreSQL数据库的方法
- PostgreSQL 大会与DBA培训交流记录
- 也谈PostgreSQL的同步配置(Slony)
- postgreSQL 维护
- PostgreSQL和Oracle用法上的一些区别
- 晨曦之光 postgreSql基础命令及linux下postgreSql命令
- PostgreSql远程连接配置
- 触发器 Trigger
- Oracle中merge into的使用
- Oracle中merge into的使用