好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

postgresql 实现replace into功能的代码

PostgreSQL 9.5-

使用函数或with实现

?

1

2

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。

?

1

2

INSERT INTO table_name VALUES () ON conflict (唯一索引字段) DO

UPDATE ...

补充:PostgreSQL中select into用法总结

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

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

比如:

?

1

2

3

4

5

6

7

8

9

10

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;

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

因该修改为如下

?

1

2

3

4

5

6

7

8

9

10

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://blog.csdn.net/weixin_39810091/article/details/105966200

查看更多关于postgresql 实现replace into功能的代码的详细内容...

  阅读:31次