1

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);

1 Answer 1

1

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 
-----
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.