当前位置:数据库 > SQLServer >>

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


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

在PG库里,除了以上方法外,还有一种更能提升性能的办法,使用perform来代替select。
 
Example:
Create or replace function test.insert_exist_test(i_id int,i_info text) 
returns void   www.zzzyk.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.zzzyk.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
Oracle
MySQL
Access
SQLServer
DB2
Excel
SQLite
SYBASE
Postgres
如果你遇到数据库难题:
请访问www.zzzyk.com 试试
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,