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?

link|improve this question

feedback

2 Answers

up vote 2 down vote accepted

Are you looking for something like this?:

SELECT * FROM :"table_name";

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

link|improve this answer
feedback

Something like this :

SELECT 'SELECT * FROM ' || countries::text AS specificQuery;
link|improve this answer
I'm not sure you've got the original idea... I have countries as a content of a variable. Anyway, I guess you mean table_name::text or :table_name::text, but none of that works. – Radek Simko May 13 at 21:19
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.