I have a command to run in pgadmin which looks like below:
SELECT format('SELECT * FROM %I.%I CROSS JOIN LATERAL json_to_record(%I::json) AS rs(%s)', 'public', 'vehicles', 'column_A', array_to_string(
(SELECT ARRAY(SELECT DISTINCT col FROM vehicles CROSS JOIN LATERAL json_object_keys(column_A::json) AS t(col) ORDER BY col)), ' text , '
) || ' text')
It prints a string starting with SELECT
statement.
How do I get the result from the query straight from the string returned by the FORMAT
?
I have tried something like:
DO
$$
WITH str as( SELECT format('SELECT * FROM %I.%I CROSS JOIN LATERAL json_to_record(%I::json) AS rs(%s)', 'public', 'vehicles', 'column_A', array_to_string(
(SELECT ARRAY(SELECT DISTINCT col FROM vehicles CROSS JOIN LATERAL json_object_keys(column_A::json) AS t(col) ORDER BY col)), ' text , '
) || ' text'))
BEGIN EXECUTE str;
END
$$
However, I got an error message saying:
ERROR: syntax error at or near "WITH"
What have I missed here? Please advise!!
Updated answer
After combining answers from the experts below, here is the updated version for future reference:
do $$
DECLARE
query text;
begin
query := format('SELECT * FROM %I.%I CROSS JOIN LATERAL json_to_record(%I::json) AS rs(%s)', 'public', 'vehicles', 'column_A', array_to_string(
(SELECT ARRAY(SELECT DISTINCT col FROM vehicles CROSS JOIN LATERAL json_object_keys(column_A::json) AS t(col) ORDER BY col)), ' text , '
) || ' text');
execute format('create or replace temp view tmp_view_vehicles as %s', query);
end $$;
select * from tmp_view_vehicles;
Thank you everyone & your patience!