Postgresql 存储过程(plpgsql)两层for循环的操作

项目中遇到测试,需要造4500数据,而且需要分部门和日期,一个部门一天30条数据,剩下的铺垫数据可以一个部门一天100w左右数据,这里,每次变换部门,日期,需要操作至少300次,想到用存储过程写一个函数进行

首先,了解存储过程的语法:

create [ or replace ] function
  name( [ [argmode] [argname]argtype[ { default | = }default_expr] [, ...] ] )
    [ returnsrettype
     | returns table (column_namecolumn_type[, ...] ) ]
  { languagelang_name
    | window
| immutable | stable | volatile
    | called on null input | returns null on null input | strict
    | [ external ] security invoker | [ external ] security definer
    | costexecution_cost
    | rowsresult_rows
    | setconfiguration_parameter{ tovalue| =value| from current }
    | as 'definition'
    | as 'obj_file', 'link_symbol'
  } ...
    [ with (attribute[, ...] ) ]
————————————————

create [ or replace ] function–创建一个函数,若有此函数,即取代重新创建 name ——-函数名称

returns—函数返回类型

具体的函数声明,请参考[postgresql存储过程]

下面说我写的函数:

create or replace function "xue"."insert_into_table"()
 returns "pg_catalog"."void" as $body$
declare tmp varchar(1024);
declare n integer;
declare i integer;
declare inst_seq_no cursor for
  select inst_seq_no from t where no in (
  '111','22','223','33','4358',
   '233','449','315','35335');
begin
  raise notice '------------start----------';
  i := 30;
  for stmt in no loop
    n := 30;
    for n in n..i loop    
      insert into test2 (no,
      test_no,time,user_no,seq_no,
      name,user_no1,user_name,code,user_no2,opror_name,
      review_time,desc,
      val1,val2,date,upd_time,del_flag) values
      (nextval('seq_test2'),n,'20190910',n,stmt.seq_no,n,n,n,n,n,n,'20190910','01','',n,n,'20190910',
      '20190909','0');
      end loop;
       n = n+30;
      i = i+30;
  end loop;
  raise notice '-----------finished---------';
end;
$body$
 language plpgsql volatile
 cost 100`

很简单的逻辑,但是在修改了三四遍才实现,这个第二次写存储过程,很多语法不是很熟悉,要注意的如:

1.`变量声明要用declare

2.“游标 cursor 的用法

3.for循环要在begin中执行,

4.循环中要用“:=”

补充:postgresql中存储过程(函数)调用存储过程(函数)时应用注意的问题

在postgresql中我们在执行存储过程中往往会使用select 存储过程,但是如果存储过程中再调用 存储过程时,就不能这样用了,应该用perform 存储过程,可以去参考官方文档的说明

执行一个没有结果的表达式或者命令

有时候我们希望计算一个表达式或者一个命令,但是却丢弃其结果(通常因为我们经常调用一些存在有用的副作用但是不存在有用结果值的函数)。 要在 pl/pgsql 里干这件事, 你可以使用perform语句:

perform query;

这条语句执行一个 query并且丢弃结果。 query 的写法和你平常写 sql select 命令是一样的, 只是把开头的关键字 select 替换成 perform。 pl/pgsql 的变量和平常一样代换到命令中。 同样,如果命令生成至少一行,那么特殊的变量 found 设置为真,如果没有生成行,则为假。

注意: 我们可能希望没有into子句的select也能满足这样的需要, 但是目前可以接受的唯一的方法是perform。

一个例子:

perform create_mv('cs_session_page_requests_mv', my_query);

以上为个人经验,希望能给大家一个参考,也希望大家多多支持www.887551.com。如有错误或未考虑完全的地方,望不吝赐教。

(0)
上一篇 2022年3月21日
下一篇 2022年3月21日

相关推荐