简体   繁体   English

如何在PostgreSQL,PL / pgSQL上执行匿名代码块切换CASE语句?

[英]How to perform an anonymous code block switch CASE statement on the PostgreSQL, PL/pgSQL?

How to perform the switch CASE statement on the PostgreSQL, PL/pgSQL? 如何在PostgreSQL,PL / pgSQL上执行switch CASE语句?

Currently we may right a IF block like this: 目前,我们可以纠正这样的IF块:

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

However it is not desired for several cases. 但是,在某些情况下是不希望的。 Then a better approach would be use something close to the usual switch statements. 然后,更好的方法是使用接近常规switch语句的内容。

Related threads: 相关主题:

  1. PostgreSQL IF statement PostgreSQL IF语句

In order to mimic a switch statement, put the switch value directly after "CASE" before the "WHEN". 为了模拟switch语句,请将switch值直接放在“ CASE”之后的“ WHEN”之前。 Every when statement will check to see if it's value equals the CASE value. 每个when语句将检查其值是否等于CASE值。

Example using the specialized case statement to return hex color values for color words: 使用专用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 $$

I'm not able to test the anonymous block on my computer so here's a straight SQL statement I've tested to work which can be used in an anonymous block: 我无法在计算机上测试匿名块,因此这是我已经测试过的可以直接在匿名块中使用的直接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;

The basic/base structure for the PL/pgSQL CASE with anonymous code block procedure block is: 具有匿名代码块过程块的PL / pgSQL CASE的基本/基本结构是:

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

References: 参考文献:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM