Postgresql function with if statement

Edi*_*ons 1 postgresql function

How can I make this pseudo code to work in Postgresql:

create or replace function getf(arg character varying(255)) returns int
as $$
if arg = 'a' then return 1;
else return 2;
$$ language sql;
Run Code Online (Sandbox Code Playgroud)

Based on argument I need to return some values and there is no other table I need to query. Just need to build a logic inside function. Tried to replace if with when clause, but could not figure out how to do it.

Thanks!

Pat*_*ick 6

create or replace function getf(arg character varying(255)) returns int as $$
begin
  if arg = 'a' then
    return 1;
  else 
    return 2;
  end if;
end; $$ language plpgsql;
Run Code Online (Sandbox Code Playgroud)

Note that this is a PL/pgSQL function.

The online manual has an excellent chapter on PL/pgSQL. That should provide everything you need to get started writing procedural function with ample support for logical branching.


Hou*_*ari 5

使用语言,您可以使用case when 来sql做到这一点:

create or replace function getf(arg character varying(255)) returns int as
 $$

select case 
        when arg = 'a' 
         then 1
         else 2 
       end

$$ language sql;
Run Code Online (Sandbox Code Playgroud)