简体   繁体   English

如何在字符串数组上运行PostgreSQL查询?

[英]How can I run a postgresql query over array of strings?

I'm writing a script which will take all tables from my schema and perform some actions on them. 我正在编写一个脚本,该脚本将从我的模式中获取所有表并对其执行一些操作。 The tables that will be taken have same prefix and different suffix. 将要使用的表具有相同的前缀和不同的后缀。 Now, what I want to do is to declare an array at the beginning of the script, the array will contain all regex for all tables that I need, for example: 现在,我要做的是在脚本的开头声明一个数组,该数组将包含我需要的所有表的所有正则表达式,例如:

base_tables varchar[2] := ARRAY['table_name_format_2%',
                            'another_format_3%'];

Using this array, I would like to go through all the tables in my schema and take only those that match the name pattern in the array. 使用此数组,我想遍历我的架构中的所有表,并仅采用那些与数组中的名称模式匹配的表。 I tried to do this as such: 我试图这样做:

FOR table_item IN
    SELECT table_name 
    FROM information_schema.tables 
    WHERE table_name LIKE IN base_tables
    LOOP 
        ---- Some code goes here -----
    END LOOP; 

The error I get is : 我得到的错误是:

ERROR: syntax error at or near "IN" 错误:“ IN”处或附近的语法错误

What is the correct way to compare each table name, to the names in my array? 将每个表名与数组中的名称进行比较的正确方法是什么?

Thanks in advance. 提前致谢。

demo:db<>fiddle 演示:分贝<>小提琴

To get a match for an array element you have to use: 要获得数组元素的匹配项,您必须使用:

-- general case
WHERE element = ANY(ARRAY['elem1', 'elem2'])

-- your case
WHERE table_name = ANY(base_tables)

If you want to achieve a LIKE eehrm... like operation you'll need another way: 如果您想实现LIKE eehrm ...之类的操作,则需要另一种方法:

SELECT table_name 
FROM information_schema.tables t
JOIN (SELECT unnest(base_tables) as name) bt
ON t.table_name LIKE bt.name

Joining tables against an unnested base_tables array ( unnest expands an array to one row for each element). 针对未嵌套的base_tables数组联接tablesunnest将每个元素的数组扩展为一行)。 You can join with the LIKE operator. 您可以加入LIKE运营商。

demo:db<>fiddle 演示:分贝<>小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM