Sintaxis de Expresión de Caso SQL?


¿Cuál es la sintaxis complete y correct para la expresión SQL Case?

Author: Tanner, 2008-08-07

8 answers

La sintaxis complete depende del motor de base de datos con el que esté trabajando:

Para SQL Server:

CASE case-expression
    WHEN when-expression-1 THEN value-1
  [ WHEN when-expression-n THEN value-n ... ]
  [ ELSE else-value ]
END

O:

CASE
    WHEN boolean-when-expression-1 THEN value-1
  [ WHEN boolean-when-expression-n THEN value-n ... ]
  [ ELSE else-value ]
END

Expresiones, etc:

case-expression    - something that produces a value
when-expression-x  - something that is compared against the case-expression
value-1            - the result of the CASE statement if:
                         the when-expression == case-expression
                      OR the boolean-when-expression == TRUE
boolean-when-exp.. - something that produces a TRUE/FALSE answer

Link: CASE (Transact-SQL)

También tenga en cuenta que el orden de las instrucciones WHEN es importante. Puede escribir fácilmente varias cláusulas WHEN que se superponen, y se utiliza la primera que coincide con.

Nota : Si no se especifica ninguna cláusula ELSE, y no hay coincidencia CUANDO se encuentra-condition, el valor de la expresión CASE será NULL.

 75
Author: Lasse Vågsæther Karlsen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-07 14:26:21

Considerando que etiquetaste varios productos, diría que la sintaxis completa correcta sería la que se encuentra en el estándar ISO / ANSI SQL-92:

<case expression> ::=
       <case abbreviation>
     | <case specification>

<case abbreviation> ::=
       NULLIF <left paren> <value expression> <comma>
              <value expression> <right paren>
     | COALESCE <left paren> <value expression>
                { <comma> <value expression> }... <right paren>

<case specification> ::=
       <simple case>
     | <searched case>

<simple case> ::=
     CASE <case operand>
          <simple when clause>...
        [ <else clause> ]
     END

<searched case> ::=
     CASE
       <searched when clause>...
     [ <else clause> ]
     END

<simple when clause> ::= WHEN <when operand> THEN <result>

<searched when clause> ::= WHEN <search condition> THEN <result>

<else clause> ::= ELSE <result>

<case operand> ::= <value expression>

<when operand> ::= <value expression>

<result> ::= <result expression> | NULL

<result expression> ::= <value expression>

Reglas de sintaxis

1) NULLIF (V1, V2) is equivalent to the following <case specification>:

     CASE WHEN V1=V2 THEN NULL ELSE V1 END

2) COALESCE (V1, V2) is equivalent to the following <case specification>:

     CASE WHEN V1 IS NOT NULL THEN V1 ELSE V2 END

3) COALESCE (V1, V2, . . . ,n ), for n >= 3, is equivalent to the
   following <case specification>:

     CASE WHEN V1 IS NOT NULL THEN V1 ELSE COALESCE (V2, . . . ,n )
     END

4) If a <case specification> specifies a <simple case>, then let CO
   be the <case operand>:

   a) The data type of each <when operand> WO shall be comparable
      with the data type of the <case operand>.

   b) The <case specification> is equivalent to a <searched case>
      in which each <searched when clause> specifies a <search
      condition> of the form "CO=WO".

5) At least one <result> in a <case specification> shall specify a
   <result expression>.

6) If an <else clause> is not specified, then ELSE NULL is im-
   plicit.

7) The data type of a <case specification> is determined by ap-
   plying Subclause 9.3, "Set operation result data types", to the
   data types of all <result expression>s in the <case specifica-
   tion>.

Access Rules

   None.

General Rules

1) Case:

   a) If a <result> specifies NULL, then its value is the null
      value.

   b) If a <result> specifies a <value expression>, then its value
      is the value of that <value expression>.

2) Case:

   a) If the <search condition> of some <searched when clause> in
      a <case specification> is true, then the value of the <case
      specification> is the value of the <result> of the first
      (leftmost) <searched when clause> whose <search condition> is
      true, cast as the data type of the <case specification>.

   b) If no <search condition> in a <case specification> is true,
      then the value of the <case expression> is the value of the
      <result> of the explicit or implicit <else clause>, cast as
      the data type of the <case specification>.
 21
Author: onedaywhen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-07 14:29:03

Aquí están los CASE ejemplos de sentencias de los documentos de PostgreSQL (Postgres sigue el estándar SQL aquí):

SELECT a,
   CASE WHEN a=1 THEN 'one'
        WHEN a=2 THEN 'two'
        ELSE 'other'
   END
FROM test;

O

SELECT a,
   CASE a WHEN 1 THEN 'one'
          WHEN 2 THEN 'two'
          ELSE 'other'
   END
FROM test;

Obviamente, la segunda forma es más limpia cuando solo está comprobando un campo contra una lista de valores posibles. La primera forma permite expresiones más complicadas.

 19
Author: Neall,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-05-17 14:12:22

Sybase tiene la misma sintaxis case que SQL Server:

Descripción

Admite expresiones SQL condicionales; se puede usar en cualquier lugar donde se pueda usar una expresión de valor.

Sintaxis

case 
     when search_condition then expression 
    [when search_condition then expression]...
    [else expression]
end

Sintaxis de mayúsculas y minúsculas

case expression
     when expression then expression 
    [when expression then expression]...
    [else expression]
end

Parámetros

Caso

Comienza la expresión case.

Cuando

Precede la condición de búsqueda o la expresión a comparar.

Condición de búsqueda

Se utiliza para establecer condiciones para los resultados que se seleccionan. Las condiciones de búsqueda para expresiones case son similares a las condiciones de búsqueda en una cláusula where. Las condiciones de búsqueda se detallan en la Guía del usuario de Transact-SQL.

Entonces

Precede a la expresión que especifica un valor de resultado de case.

Expresión

Es un nombre de columna, una constante, una función, una subconsulta o cualquier combinación de nombres de columna, constantes y funciones conectadas por operadores aritméticos o bitwise. Para más información sobre expresiones, consulte "Expresiones" en.

Ejemplo

select disaster, 
       case
            when disaster = "earthquake" 
                then "stand in doorway"
            when disaster = "nuclear apocalypse" 
                then "hide in basement"
            when monster = "zombie apocalypse" 
                then "hide with Chuck Norris"
            else
                then "ask mom"
       end 
  from endoftheworld
 8
Author: Eric Johnson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-03-26 19:05:29

He desenterrado la página de Oracle para el mismo y parece que esta es la misma sintaxis, sólo descrito ligeramente diferente.

Link: Oracle / PLSQL: Case Statement

 4
Author: Lasse Vågsæther Karlsen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-01-27 12:59:50

Sintaxis de Oracle de la documentación 11g :

CASE { simple_case_expression | searched_case_expression }
     [ else_clause ]
     END

Simple_case_expression

expr { WHEN comparison_expr THEN return_expr }...

Searched_case_expression

{ WHEN condition THEN return_expr }...

Else_clause

ELSE else_expr
 3
Author: Leigh Riffel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-08-10 15:26:31

Un punto a tener en cuenta en el caso de Oracle, si no cuando coincide y no hay otra parte se plantea una excepción.

 1
Author: Tanveer Badar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-02-01 07:19:45

Sintaxis de sentencia Case en SQL SERVER:

CASE column
   WHEN value1 THEN 1
   WHEN value3 THEN 2
   WHEN value3 THEN 3
   WHEN value1 THEN 4
   ELSE ''
END

Y podemos utilizar como a continuación también:

CASE 
   WHEN column=value1 THEN 1
   WHEN column=value3 THEN 2
   WHEN column=value3 THEN 3
   WHEN column=value1 THEN 4
   ELSE ''
END
 -2
Author: user2001117,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-24 17:47:31