PL/pgSQL CASE 语句
总结:在本教程中,您将了解 case 基于特定条件执行语句的 PL/pgSQL 。
除了if 语句之外,PostgreSQL 还为您提供 case 了允许您根据条件执行代码块的语句。
该 case 语句根据条件 when 从 when 节列表中选择要执行的节。
该 case 声明有两种形式:
- 简单的
case语句 - 搜索
case语句
请注意,您不应混淆 case 语句和case 表达式。的 case 表达式计算为一个值,而 case 语句选择一个部分执行基于条件。
1)简单的case语句
让我们从简单 case 语句的语法开始:
case search-expression
when expression_1 [, expression_2, ...] then
when-statements
[ ... ]
[else
else-statements ]
END case;
的 search-expression 是计算结果为结果的表达式。
该 case 语句使用相等运算符 ( ) 从上到下比较每个分支中的 search-expression 和的结果。 expression when =
如果 case 语句找到匹配项,它将执行相应的 when 部分。此外,它停止将 的结果 search-expression 与其余表达式进行比较。
如果 case 语句找不到任何匹配项,它将执行该 else 部分。
该 else 部分是可选的。如果对结果 search-expression 不相符 expression 的 when 部分和 else 部分不存在的情况下语句会抛出一个 case_not_found 异常。
以下是简单 case 语句的示例。
do $$ declare
rate film.rental_rate%type;
price_segment varchar(50);
begin
-- get the rental rate
select rental_rate into rate
from film
where film_id = 100;
-- assign the price segment
if found then
case rate
when 0.99 then
price_segment = 'Mass';
when 2.99 then
price_segment = 'Mainstream';
when 4.99 then
price_segment = 'High End';
else
price_segment = 'Unspecified';
end case;
raise notice '%', price_segment;
end if;
end; $$
输出:
NOTICE: High End
此示例首先选择 id 为 100 的电影。它根据租用率为电影分配一个价格段,可以是大众、主流或高端。如果价格不是 0.99、2.99 或 4.99,则该 case 语句将价格段指定为未指定的电影。
以下流程图说明了 case 此示例中的简单语句:

2) 搜索到的 case 语句
以下语法显示了搜索 case 语句的语法:
case
when boolean-expression-1 then
statements
[ when boolean-expression-2 then
statements
... ]
[ else
statements ]
end case;
在此语法中,该 case 语句从上到下按顺序计算布尔表达式,直到找到计算结果为 true
一旦找到计算结果为 的表达式, true case 语句就会执行相应的 when 部分并立即停止搜索剩余的表达式。
如果没有表达式的计算结果为真,则该 case 语句将执行该 else 部分。
该 else 部分是可选的。如果省略 else 部分并且没有表达式计算为 true ,则该 case 语句将引发 case_not_found 异常。
以下示例说明了如何使用简单 case 语句:
do $$ declare
total_payment numeric;
service_level varchar(25) ;
begin
select sum(amount) into total_payment
from Payment
where customer_id = 100;
if found then
case
when total_payment > 200 then
service_level = 'Platinum' ;
when total_payment > 100 then
service_level = 'Gold' ;
else
service_level = 'Silver' ;
end case;
raise notice 'Service Level: %', service_level;
else
raise notice 'Customer not found';
end if;
end; $$
这个怎么运作:
- 首先,从
payment表中选择客户 ID 100 支付的总付款。 - 然后,根据总付款将服务级别分配给客户
下图说明了逻辑:

请注意,搜索 case 到的语句类似于if then elsif 语句。
在本教程中,您学习了如何使用 case 基于特定条件执行语句的 PL/pgSQL 。