Radek Simko
Radek Simko

Reputation: 16126

How to express PostgreSQL variable as a string

Is there any way how to express a variable in PostgreSQL as a string?

Example:

\set table_name countries
SELECT 'SELECT * FROM ' || CAST( :table_name, 'text' ) AS specificQuery;

leads to this error:

ERROR:  syntax error at or near ","
LINE 1: SELECT 'SELECT * FROM ' || CAST( countries, 'text' ) AS specificQuery;

From the line sample above is obvious, that it doesn't convert "countries" to a string, but it is expressed as name of column/table.

How do I convert it?

Upvotes: 3

Views: 10050

Answers (2)

kgrittn
kgrittn

Reputation: 19471

Are you looking for something like this?:

SELECT * FROM :"table_name";

http://www.postgresql.org/docs/current/interactive/app-psql.html#APP-PSQL-VARIABLES

Upvotes: 9

aleroot
aleroot

Reputation: 72626

Something like this :

SELECT 'SELECT * FROM ' || countries::text AS specificQuery;

Upvotes: 2

Related Questions