Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Concatenation with variable in function gives an error

So I am trying to run this function.

CREATE OR REPLACE FUNCTION TableIteration() 
  RETURNS TABLE(table_schema text, table_name text)
  LANGUAGE plpgsql
AS
$$
DECLARE 
    tgt_schema varchar;
    list text[] := ARRAY[
    "text1",
    "text2",
    "text3",
    "text4",
    "text5",
    "text6",
    "text7",
    "text8",
    "text9"
];
BEGIN
    FOREACH tgt_schema IN ARRAY list
        LOOP
        RETURN QUERY EXECUTE
        'SELECT t.table_schema :: text, t.table_name::text from information_schema.tables t
        WHERE t.table_schema :: text='||tgt_schema; 
        END LOOP;
    END
$$

But somehow concatenation gives me not what I was expected.

Everytime I launch function I am getting error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

‘ERROR: column "text1" does not exist’

Why postgres interprets my variable as column?

>Solution :

Use single quotes for declared array elements and the function format() with a proper placeholder for literals %L:

    ...
    RETURN QUERY EXECUTE format(
    'SELECT 
        t.table_schema :: text, 
        t.table_name::text 
    FROM information_schema.tables t
    WHERE t.table_schema :: text = %L', tgt_schema); 
    ...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading