首页 > 解决方案 > 循环每个数组的项 Postgresql

问题描述

我有一个函数,我想在其中循环抛出每个数组的项目。我在输入中得到一个字符串,例如'tab1#tab2#tab3'...字符串的每个项目都必须拆分(按#),以便将tab1、tab2、tab3 获取到myArray 中。我的功能是:

CREATE OR REPLACE FUNCTION funcA(
myUid integer,
mytable_name varchar,
state varchar)
RETURNS void AS

$BODY$


declare

TABarray varchar[];
indx int;

BEGIN  


    select REGEXP_REPLACE('{'||myTABLE_NAME||'}','#','','g') into TABarray;


    for indx in 1..array_length(TABarray, 1) loop

    execute 'update ' || TABarray(indx) || ' set CODE_STATO = ''' || state || ''' where uid = ' ||  myUid || 'and CODE_STATO <> ''N'' ';
    raise notice 'i: %', TABarray[ indx ];

    end loop;

    END; $BODY$
    LANGUAGE plpgsql stable

结果,我期望 3 个拆分字符串,例如:

-tab1

-tab2

-tab3

现在 myFunction 打印 {tab1tab2tab3}。

   select oms_write_stato (10, 'tab1#tab2#tab3', '')

我做错了什么?

先感谢您!

标签: postgresqlfunctionplpgsql

解决方案


PL/pgSQL 有用FOREACH IN ARRAY于此目的的语句:

你的任务可以写成这样:

-- Don't use case mixed identifiers (prohibit camel notation)
create or replace function funca(uid integer,
                                 tablenames varchar,
                                 state varchar)
returns void as $$
declare tablename text;
begin
  foreach tablename in array string_to_array(tablenames, '#')
  loop
    execute format('update %I set code_stato = $1 where uid = $2 and code_state <>'N',
                   tablename)
      using state, uid;
  end loop;
end;
$$ language plpgsql;

笔记:

  1. 不要在标识符中混合上下字符
  2. 不要混合大写/小写关键字 - 有一些变体 - 关键字由大写或全部小写,但混合不利于阅读
  3. 当您使用动态 SQL 时,请在将数据用于动态查询之前对其进行清理 - 使用quote_identquote_literal函数或format带有安全占位符的函数,并在可能的情况下传递 withUSING子句。
  4. postgres 具有数组类型 -str1#str2#str3#str4在 Postgres 中使用有点模糊 - 使用原生数组,如ARRAY['str1','str2','str3','str4'].

推荐阅读