简体   繁体   中英

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?

Currently we may right a IF block like this:

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.

Related threads:

  1. PostgreSQL IF statement

In order to mimic a switch statement, put the switch value directly after "CASE" before the "WHEN". Every when statement will check to see if it's value equals the CASE value.

Example using the specialized case statement to return hex color values for color words:

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:

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:

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
  2. https://www.postgresql.org/docs/current/static/plpgsql-control-structures.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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