PostgreSQL的case语句

PostgreSQL的case语句
1、语法:
case var
when condition1 then statement1;
when condition2 then statement2;
eles statementn;
...
end case;

案例1:
create or replace function get_price_segment(p_film_id integer)
returns varchar(50) as $$
declare 
    rate numeric;
    price_segment varchar(50);
begin 
    select into rate rental_rate from film where film_id = p_film_id;
    case rate
    when 0.99 then price_segment='0.99';
    when 2.99 then price_segment='2.99';
    when 4.99 then price_segment='4.99';
    else price_segment='much';
    end case;
    return price_segment;
end; $$
language plpgsql;

select get_price_segment(3);


2、语法:
case
when boolean-exepression1 then statement1;
when boolean-exepression2 then statement2;
...
else statementN;
end case;

案例:
create or replace function get_customer_service(p_customer_id integer)
returns varchar(50) as $$
declare
    total_payment numeric;
    service_level varchar(50);
begin
    select into total_payment sum(amount) from payment where customer_id=p_customer_id;
    case 
    when total_payment>200 then service_level='platinum';
    when total_payment>100 then service_level='gold';
    else service_level='sliver';
    end case;
    return service_level;

end; $$
language plpgsql;


select get_customer_service(344);

你可能感兴趣的:(PostgreSQL的case语句)