Re: psql \set variables in crosstab queries? - Mailing list pgsql-general

From Ron
Subject Re: psql \set variables in crosstab queries?
Date
Msg-id 50b9a782-09a3-e109-b687-90ad96755274@gmail.com
Whole thread Raw
In response to Re: psql \set variables in crosstab queries?  ("David G. Johnston" <david.g.johnston@gmail.com>)
Responses Re: psql \set variables in crosstab queries?  ("David G. Johnston" <david.g.johnston@gmail.com>)
List pgsql-general
On 3/4/23 19:32, David G. Johnston wrote:
On Sat, Mar 4, 2023 at 5:20 PM Ron <ronljohnsonjr@gmail.com> wrote:

But crosstab takes text strings as parameters.  How then do you use \set
variables in crosstab queries?


You need to dynamically write the textual query you want to send to the crosstab function.  In particular that means writing it using "format()" and then substituting the values into the query via placeholders.

Roughly like:

SELECT * FROM crosstab(format('SELECT * FROM %I WHERE %I = %L, :'tbl_name', :'col_name', :'compare_value'));

David J.


Ugh.  It's a long and hairy query that would be a nightmare in a format statement.

--
Born in Arizona, moved to Babylonia.

pgsql-general by date:

Previous
From: Ron
Date:
Subject: Re: psql \set variables in crosstab queries?
Next
From: "David G. Johnston"
Date:
Subject: Re: psql \set variables in crosstab queries?