postgresql - 循环每个数组的项 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', '')
我做错了什么?
先感谢您!
解决方案
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;
笔记:
- 不要在标识符中混合上下字符
- 不要混合大写/小写关键字 - 有一些变体 - 关键字由大写或全部小写,但混合不利于阅读
- 当您使用动态 SQL 时,请在将数据用于动态查询之前对其进行清理 - 使用
quote_ident
、quote_literal
函数或format
带有安全占位符的函数,并在可能的情况下传递 withUSING
子句。 - postgres 具有数组类型 -
str1#str2#str3#str4
在 Postgres 中使用有点模糊 - 使用原生数组,如ARRAY['str1','str2','str3','str4']
.
推荐阅读
- ios - 'exported: true' 在 Xcode 12.5 中的 '_specialize' 属性中无效
- python - 尝试从文本文件向 Telegram 发送消息
- sql - 仅在特定日期之后获取即时版本的条件查询
- java - 获取输入流中 STX 和 ETX 之间的字符串/字节
- android - MACOS M1 Big Sur 11.3 - 运行 Android Studio 4.1.3 的问题 - 问题 W/Nexus 6 API 28 模拟器
- facebook-graph-api - GraphQL Java 中的持久查询支持
- arduino - 串行监视器字体arduino无法显示
- python - Pandas to_csv 只写入来自特定页面的数据
- javascript - 使用 PHP 和 JQuery 在 Wordpress 中具有多个输入的 Ajax 搜索表单 数据获取
- node.js - Nodejs等待mysql2结果,然后继续执行