Question

How to use nested CASE conditional expression in function using PostgreSQL?

For example the following function is created to calculate two numbers:

create or replace function fun(n integer) returns void as
$body$
declare
   a int :=10;
   b int :=5;
   addition int :=0;
   subs int :=0;

begin
   select n,
   case when n=1 then
   addition:=a+b;
   raise info '%',addition;

   case when n=2 then
   subs:=a-b;
   raise info '%',subs;

   end
end;
$body$
language plpgsql;

--Calling function

select fun(1);
Was it helpful?

Solution

You can't have a command inside the case. Use the case as a parameter to raise.

create or replace function fun(n integer) returns void as
$body$
declare
    a int := 10;
    b int := 5;

begin
    raise info '%', case n
        when 1 then a + b
        else a - b
        end
    ;
end;
$body$
language plpgsql;

select fun(1);
INFO:  15
 fun 
-----

(1 row)

select fun(2);
INFO:  5
 fun 
-----
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top