【问题标题】:How to perform an anonymous code block switch CASE statement on the PostgreSQL, PL/pgSQL?如何在 PostgreSQL、PL/pgSQL 上执行匿名代码块切换 CASE 语句?
【发布时间】:2016-11-28 21:25:27
【问题描述】:

如何在PostgreSQL、PL/pgSQL上执行switch CASE语句?

目前我们可以像这样对一个 IF 块:

IF boolean THEN
    statements;
ELSE 
IF boolean THEN
    statements;
ELSE 
   statements;
END IF;
END IF;

但是,在某些情况下并不需要它。那么更好的方法是使用与通常的 switch 语句接近的东西。

相关话题:

  1. PostgreSQL IF statement

【问题讨论】:

  • 请注意,您可以在示例中使用 ELSIF 语句而不是两个单独的 IF/ELSE/END IF 语句。

标签: postgresql plpgsql


【解决方案1】:

为了模仿 switch 语句,将 switch 值直接放在“CASE”之后的“WHEN”之前。每个 when 语句都会检查它的值是否等于 CASE 值。

使用专用 case 语句返回颜色词的十六进制颜色值的示例:

DO $$ 
DECLARE
  test_color varchar;
  hex_color varchar;
BEGIN
  test_color := 'blue';
  hex_color :=
    CASE test_color
      WHEN 'red' THEN
        '#FF0000'
      WHEN 'blue' THEN
        '#0000FF'
      WHEN 'yellow' THEN
        '#FFFF00'
      ELSE --we do not use that color, replace with white
        '#FFFFFF'
    END;
END $$

我无法在我的计算机上测试匿名块,所以这是我测试过的可以在匿名块中使用的直接 SQL 语句:

SELECT
    CASE 'blue'
      WHEN 'red' THEN
        '#FF0000'
      WHEN 'blue' THEN
        '#0000FF'
      WHEN 'yellow' THEN
        '#FFFF00'
      ELSE --we do not use that color, replace with white
        '#FFFFFF'
    END;

【讨论】:

    【解决方案2】:

    带有anonymous code block 过程块的PL/pgSQL CASE 的基本/基本结构是:

    DO $$ BEGIN
        CASE
            WHEN boolean-expression THEN
              statements;
            WHEN boolean-expression THEN
              statements;
            ...
            ELSE
              statements;
        END CASE;
    END $$;
    

    参考文献:

    1. http://www.postgresql.org/docs/current/static/sql-do.html
    2. https://www.postgresql.org/docs/current/static/plpgsql-control-structures.html

    【讨论】:

      猜你喜欢
      • 2021-02-01
      • 1970-01-01
      • 2017-09-02
      • 2019-12-18
      • 1970-01-01
      • 1970-01-01
      • 2016-04-27
      • 1970-01-01
      • 2014-09-30
      相关资源
      最近更新 更多