postgresql实现replace into功用的代码

这篇文章主要介绍了postgresql 实现replace into功能的代码,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧。
 
PostgreSQL 9.5-
 
使用函数或with实现
 
create table test(id int primary key, info text, crt_time timestamp);
with upsert as (update test set info='test',crt_time=now() where id=1 returning *) insert into test select 1,'test',now() where not exists (select 1 from upsert where id=1);
 
 
 
PostgreSQL 9.5+
 
PostgreSQL 9.5 引入了一项新功能,UPSERT(insert on conflict do),当插入遇到约束错误时,直接返回,或者改为执行UPDATE。
 
INSERT INTO table_name VALUES() ON conflict (唯一索引字段) DO
UPDATE …
以上情况会报错。。。。。
 
因该修改为如下
 
create or replace FUNCTION test () RETURNS void AS
$body$
DECLARE
toalnum int;
BEGIN
execute 'select sum(colname)' into totalnum;
return;
END;
$body$
LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER
【声明】:茂名站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。

相关文章