I have a use case where new client tables are being created daily and I need a way to automate the creation of a union job to include new client tables as they are created. I can use the following query to search for all tables based on their name:
SELECT *
FROM "INFORMATION_SCHEMA"."TABLES"
WHERE
TABLE_SCHEMA = 'CLIENTS'
/*Update these fields*/
AND TABLE_NAME ilike 'amazon_mws_%^_AllListingsReport' ESCAPE '^'
AND TABLE_TYPE = 'BASE TABLE'
),
queries AS (
SELECT *,
$$SELECT *, 'TABLE_NAME' as table_name FROM SCHEMA."TABLE_NAME"$$ AS sql_template,
replace(sql_template, 'SCHEMA', table_info.TABLE_SCHEMA) AS sql_with_schema,
replace(sql_with_schema, 'TABLE_NAME', table_info.TABLE_NAME) AS sql_with_table,
sql_with_table AS final_sql_statement
FROM table_info
)
SELECT
listagg(final_sql_statement,'\nUNION ALL\n') WITHIN GROUP ( ORDER BY TABLE_SCHEMA, TABLE_CATALOG)
FROM queries;```