0

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"

What is the correct way to compare each table name, to the names in my array?

Thanks in advance.

0

1 Answer 1

1

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:

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). You can join with the LIKE operator.

demo:db<>fiddle

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.