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

来源:未知 责任编辑:责任编辑 发表时间:2013-11-17 14:41 点击:

PostgreSQL查询表中是否存在值的优化
 
经常会碰到这么一个应用:往表里更新数据前先查询一遍被更新的数据存不存在。通常我们的做法是使用select 查询过滤一遍,然后再决定是否更新,怎么更新。

在PG库里,除了以上方法外,还有一种更能提升性能的办法,使用perform来代替select。
 
Example:
Create or replace function test.insert_exist_test(i_id int,i_info text) 
returns void   www.2cto.com  
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;  www.2cto.com  
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');
 
 
 
作者 kenyon
    发表评论
    请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
    用户名: 验证码:点击我更换图片
    最新评论 更多>>

    推荐热点

    • Request.ServerVariables 参数大全
    • 执行全文索引时出现权限不足的解决方法
    • 导入excel文件处理流程节点的解决方案
    • 查看sql修改痕迹(SQL Change Tracking on Table)
    • App数据层设计及云存储使用指南
    • PostgreSQL启动过程中的那些事三:加载GUC参数
    • MongoDB安装为Windows服务方法与注意事项
    • Percolator与分布式事务思考(二)
    • 写给MongoDB开发者的50条建议Tip1
    网站首页 - 友情链接 - 网站地图 - TAG标签 - RSS订阅 - 内容搜索
    Copyright © 2008-2015 计算机技术学习交流网. 版权所有

    豫ICP备11007008号-1