Skip to main content
Question

How to access variable name inside single quotes.

  • April 27, 2020
  • 2 replies
  • 11 views

rajatpaliwal86
Forum|alt.badge.img+2

we have a database setup script where we set the schema name at just one place. like:
\set schema_name 'athena'
and later uses it other places like
create table if not exists :schema_name.foo (....);
There are some places where we need to access schema_name variable inside singe quotes.
select refresh(':schema_name.foo');
select analyze_statistics(':schema_name.foo');

How can I access variable name inside single quotes?

2 replies

marcothesane
Forum|alt.badge.img+1
  • Participating Frequently
  • April 27, 2020

Some try-and-error brought me to this possibility:
Put the table name into another variable, then it could work ..., like here ...

\set schema_name public
\set table_name foo
\set obj_s '''':schema_name'.':table_name''''
\echo :obj_s
-- out 'public.foo'
select count(*) from :schema_name.foo;
-- out  count 
-- out -------
-- out     42
select analyze_statistics(:obj_s);
-- out  analyze_statistics 
-- out --------------------
-- out                   0


rajatpaliwal86
Forum|alt.badge.img+2
  • Author
  • Participating Frequently
  • April 27, 2020

@marcothesane said:
Some try-and-error brought me to this possibility:
Put the table name into another variable, then it could work ..., like here ...

\set schema_name public
\set table_name foo
\set obj_s '''':schema_name'.':table_name''''
\echo :obj_s
-- out 'public.foo'
select count(*) from :schema_name.foo;
-- out  count 
-- out -------
-- out     42
select analyze_statistics(:obj_s);
-- out  analyze_statistics 
-- out --------------------
-- out                   0

cool!!