postgre 数据库之存储过程示例

      postgre 数据库之存储过程示例无评论

Postgre数据库,一般的数据库操作跟其他mysql, oracle 的sql语句的写法类似,只是个别的函数和关键字写法不同而已,这里是最近做的关于存储过程操作的一个简单示例,用到一些常用的数据库编程知识,此文做个简单的介绍。

  1. 函数声明
    1. function 做函数声明
    2. select update_info()做函数调用
    3. drop function update_info() 删除函数
  2. 变量赋值
    1. select xxx into var //把查询结果赋值给变量var
    2. declare 中声明变量
  3. 返回值
    1. returns {返回值类型}
  4. 逻辑判断
    1. if … then … else … end if, 做逻辑判断
    2. 判断条件跟一般的sql判断一样
  5. 异常处理
    1. exception 做异常处理
    2. raise 做异常抛出
  6. 数据的处理
    1. 在逻辑快里边做数据的CRUD
    2. uuid 函数, 需安装扩展  create extension "uuid-ossp"

      select uuid_generate_v4();

    3. 当前时间:

      select now()::timestamp(0)without time zone

示例需求查询info表满足条件的记录,遍历这些记录,并插入area_item记录,把info的字段内容插入到area_item里边,然后把area_item.id存入info表中。

存储过程示例如下

CREATE OR REPLACE FUNCTION update_info()

RETURNS varchar as $$

declare

  V_RECORD info;

  V_SUCCESS_COUNT int;

  area_id varchar;

  result_code varchar;

  nowDate timestamp without time zone;

begin

V_SUCCESS_COUNT := 0;

for V_RECORD in (select * from info where area_item like ‘POLYGON%’) loop

begin

select uuid_generate_v4() into area_id;

V_SUCCESS_COUNT = V_SUCCESS_COUNT + 1;

select now()::timestamp(0)without time zone into nowDate;

if area_id is not null then

insert into area_item(id, area, area_type, area_name, description, last_update_date_time, last_updater)

values(area_id, V_RECORD.area_location, ‘device’, V_RECORD.id, V_RECORD.item_info, nowDate, ‘tester’);

update info set area_location = area_id where id = V_RECORD.id;

result_code = area_id;

raise notice ‘update info %’, V_RECORD.id;

end if;

   EXCEPTION

    WHEN others THEN    

    RAISE EXCEPTION ‘(%)’, V_SUCCESS_COUNT;

end;

   end loop;

   return result_code;

end;

$$ LANGUAGE plpgsql;

沟通交流合作请加微信!