微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

经常会碰到这么一个应用:往表里更新数据前先查询一遍被更新的数据存不存在。通常我们的做法是使用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');

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐