How can I get the label of each column in a result set to prepend the name if its table?
I want this to happen for queries on single tables as well as joins.
To get the VIEW
(Daryl's idea) in a single statement use a function or a 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 a command of the form:
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;
Would be less hassle to concatenate legal column names with '_' instead of '.'. But you need to be prepared for non-standard names that require double-quoting (and defend against possible SQL injection) anyway.
You can optionally provide a schema-qualified table name (myschema.person
). The schema-name is prefixed in column names automatically if it is outside the current search_path.
For repeated use, you wrap this into a plpgsql function and make the table name a text
parameter. All text-to-code conversion is sanitized here to prevent SQL injection. Example with more information here:
And you might use the new to_regclass()
in Postgres 9.4+: