0

I have a database with multiple schemas which have the same tables and views, and I want to create a procedure that creates a view from one the views in the schema.

CREATE OR REPLACE FUNCTION create_summary_view(
 created_view character varying,
 common_view character varying,
 schema_1 character varying, 
 schema_2 character varying, 
 schema_3 character varying,
 ...
 schema_x character varying, 
)

create_view is the view that will be created, common_view is the view that is identical in all the schemas, and schema_x are the list of schemas whose common_views are being joined into created_view.

Does pl/pgsql have a syntax for indicating a variable number of parameters? created_view, common_view and at least one schema_x is required?

An alternative I'm considering it to pass a comma or space separated string of the schemas and use regexp_split_to_array to break it up, but it would be good to know of variable length arguments are possible.

asked Nov 20, 2023 at 8:00

1 Answer 1

1

Create a variadic function like this:

CREATE OR REPLACE FUNCTION create_summary_view(
 created_view text,
 common_view text,
 VARIADIC schemas text[]
) RETURNS text
 LANGUAGE sql AS
$$SELECT format('CREATE VIEW %I AS ', created_view) ||
 string_agg(
 format('SELECT * FROM %I.%I', schemas[i], common_view),
 ' UNION ALL '
 )
FROM generate_series(1, cardinality(schemas)) AS i$$;

Here is an invocation:

SELECT create_summary_view('newv', 'oldv', 's1', 's2', 's3');
 create_summary_view 
═══════════════════════════════════════════════════════════════════════════════════════════════════════════
 CREATE VIEW newv AS SELECT * FROM s1.oldv UNION ALL SELECT * FROM s2.oldv UNION ALL SELECT * FROM s3.oldv
(1 row)
answered Nov 20, 2023 at 21:07
1
  • Laurenz thanks for the additional example of the view Commented Nov 21, 2023 at 9:08

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.