jeudi 29 juillet 2021

Run query based on variable

In PG, I need to get results from a different query based on the value of a variable.

I tried something like this -

do $$
declare myVar int;
select <something> into myVar;
if myVar = 1 then
    select col1 from myTable;
else
    select col2 from myTable;
end if;
end $$;

This gives me:

ERROR:  query has no destination for result data
HINT:  If you want to discard the results of a SELECT, use PERFORM instead.

Now, I can't do case because depending on myVar, myTable might have the column col1 or col2; not both. Using case will fail with "column does not exist" since it considers the whole statement and notices the non existing column.

I'm hoping IF-ELSE will help by avoiding the block with the incorrect (non-existing) column

Aucun commentaire:

Enregistrer un commentaire