postgresql 实现replace into功能的代码

postgresql 实现replace into功能的代码,第1张

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 ...

补充:PostgreSQL中select into用法总结

在普通的sql中,postgresql支持seelct......into......

但是动态调用时候不支持select......into......

比如:

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;

以上情况会报错。。。。。

因该修改为如下

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;

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。如有错误或未考虑完全的地方,望不吝赐教。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/sjk/888872.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-14
下一篇 2022-05-14

发表评论

登录后才能评论

评论列表(0条)

保存