3

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?

2 Answers 2

9

Are you looking for something like this?:

SELECT * FROM :"table_name";

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

Sign up to request clarification or add additional context in comments.

1 Comment

Using single quotes also works when you need a string: SELECT 1 WHERE column = :'table_name';. Also for concatenation: SELECT 'abc_' || :'table_name' || '_xyz';.
2

Something like this :

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

1 Comment

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.

Your Answer

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.