Postgres: SQL Error 42601: syntax error while concatenating TEXT
23:09 26 May 2026

Getting the below error when trying to

\[42601\] ERROR: syntax error at or near "$3" in context "||  $2  AS  $3", at line 1
  
  Where: PL/pgSQL function "create_internal_tables" line 19 at SQL statement

run the below procedure to create tables

NOTE: I even tried with v_tgt_tab and v_src_tab declared as VARCHAR(50) but same error.

CREATE OR REPLACE PROCEDURE create_internal_tables()
AS $$
DECLARE
    v_tgt_tab TEXT;
    v_src_tab TEXT;
    CNT INT = 0;
    wh_tab_rec RECORD;
BEGIN
FOR wh_tab_rec IN
            (
                SELECT  COALESCE(a.schema_name, b.schema_name) as schema_name,
                        COALESCE(a.table_name, b.table_name) as table_name
                FROM svv_all_tables AS a RIGHT OUTER JOIN svv_all_tables b
                ON  a.schema_name = b.schema_name AND
                    a.table_name = b.table_name
                WHERE   a.database_name = 'nonprod'
                AND     b.database_name = 'warehouse'
                ORDER BY b.schema_name, b.table_name
            )
    LOOP
       SELECT 'nonprod.' || wh_tab_rec.schema_name || '.tmp_' || wh_tab_rec.table_name AS v_tgt_tab;
       SELECT 'warehouse.' || wh_tab_rec.schema_name || '.' || wh_tab_rec.table_name AS v_src_tab;
        RAISE INFO 'Creating destination internal table %', v_tgt_tab;
        EXECUTE ('CREATE TABLE %I AS SELECT * FROM %I WHERE 1=0', v_tgt_tab, v_src_tab );
        CNT := CNT + 1;
    END LOOP;
    RAISE NOTICE '% internal tables created in destination.', CNT;
END;
$$ LANGUAGE plpgsql;

CALL create_internal_tables();
postgresql amazon-redshift