To get the VIEW ( Daryl idea ) in a single expression , use a function or DO command with EXECUTE :
DO $do$ BEGIN EXECUTE ( SELECT format( 'CREATE TEMP VIEW people AS SELECT %s FROM %I' , string_agg(format('%I AS %I', attname, attrelid::regclass || '.' || attname), ', ') , attrelid::regclass) FROM pg_attribute WHERE attrelid = 'person'::regclass -- supply source table name once AND attnum > 0 AND NOT attisdropped GROUP BY attrelid ); END $do$;
This immediately executes the form command:
CREATE OR REPLACE VIEW people AS SELECT person_id AS "person.person_id" , first_name AS "person.first_name" , last_name AS "person.last_name" FROM person;
It would be less hassle to concatenate the column names in the field "_" instead of ".". But you should be prepared for non-standard names, which in any case require double quotation (and protection against a possible SQL injection).
You can also specify the name of the table with the table ( myschema.person ). The schema name is automatically added to the column names if it is outside the current search_path .
For repeated use, you transfer this to the plpgsql function and create the table name a text . All text to code conversions are sanitized here to prevent SQL injection. An example with more information is here:
- Table name as parameter of PostgreSQL function
And you can use the new to_regclass() in Postgres 9.4 +:
- How to check if a table exists in a given schema
Erwin brandstetter
source share