I am building a query for a report and it has a lot of repeated const values in calculated columns. Simplified example:
select
c.title || ' corp', -- more than one column appending this
to_char(c.last_contact, 'YYYY-MM-DD HH24:MI') -- this format is used for other columns as well
from clients c;
I want to extract those repeated const values into variables and use variables instead. In TSQL I could achieve it with code like this:
declare
@suffix varchar(8) = ' corp',
@dateFormat varchar(16) = 'YYYY-MM-DD HH24:MI' -- let's pretend that's a correct format string for TSQL
select
c.title + @suffix,
convert(varchar(32), c.last_contact, @dateFormat)
from clients c
I'm trying to achieve same behavior in pl/pgsql with this:
do $$
declare
suffix text := ' corp';
date_format text := 'YYYY-MM-DD HH24:MI';
begin
select
c.title || suffix,
to_char(c.last_contact, date_format)
from clients c;
end;
$$;
And it breaks:
ERROR: query has no destination for result data
Hint: If you want to discard the results of a SELECT, use PERFORM instead.
Where: PL/pgSQL function inline_code_block line 5 at SQL statement
1 statement failed.
So far I've only found examples of using variables in WHERE block, but none in SELECT block.
I've seen EXECUTE 'select ...' WITH
examples, but my quick attempt of using that
do $$
declare
process_start timestamp := now();
begin
execute 'select $1;'
using process_start;
end;
$$;
just reports DO executed successfully
without actually selecting anything.
Is there a way to use pl/pgsql variables in calculated columns?
Any other alternatives to achieve this in postgres?