加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

PostgreSQL查询表中是否存在值的优化

发布时间:2020-12-13 17:46:34 所属栏目:百科 来源:网络整理
导读:经常会碰到这么一个应用:往表里更新数据前先查询一遍被更新的数据存不存在。通常我们的做法是使用select 查询过滤一遍,然后再决定是否更新,怎么更新。在PG库里,除了以上方法外,还有一种更能提升性能的办法,使用perform来代替select。 Example: Create

经常会碰到这么一个应用:往表里更新数据前先查询一遍被更新的数据存不存在。通常我们的做法是使用select 查询过滤一遍,然后再决定是否更新,怎么更新。在PG库里,除了以上方法外,还有一种更能提升性能的办法,使用perform来代替select。

Example:

Create or replace function test.insert_exist_test(i_id int,i_info text)

returns void

as

$BODY$

--author: kenyon --created:2012_03_05 --purpose:test insert into a table if exists declare begin perform 1 from test.exists_test where id = i_id; if not found then insert into test.exists_test(id,info) values (i_id,i_info); return; else update test.exists_test set info=i_info where id=i_id; return; end if; exception when others then raise exception 'Insert exists_test(id,info) values(%,%) error.',i_id,i_info; return; end; $BODY$ language plpgsql;


使用:

select test.insert_exist_test(1,'kevin'); select test.insert_exist_test(2,'BruceLee'); select test.insert_exist_test(3,'Jacky'); select test.insert_exist_test(1,'kenyon');

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读