|
The CASE statement goes through conditions and returns a value when the first condition is met (like an COBOL Evaluate statement).
So, If a condition is true, it will stop reading and return the result.
If no conditions are true, it returns the value in the ELSE clause.
If ELSE part is not added in CASE statement and no conditions are true, it returns NULL value.
A instrução CASE passa pelas condições e retorna um valor quando a primeira condição é atendida (como uma instrução COBOL Evaluate).
Portanto, se uma condição for verdadeira, ele interromperá a leitura e retornará o resultado.
Se nenhuma condição for verdadeira, ele retornará o valor na cláusula ELSE.
Se a parte ELSE não for adicionada na instrução CASE e nenhuma condição for verdadeira, ele retornará o valor NULL.
syntax - Sintaxe:
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
WHEN conditionN THEN resultN
ELSE result
END;
|
The following SQL goes through several conditions and returns a value when the specified condition is met:
O seguinte SQL passa por várias condições e retorna um valor quando a condição especificada é atendida:
SELECT OrderID, Quantity,
CASE
WHEN Quantity > 30 THEN "The quantity is greater than 30"
WHEN Quantity = 30 THEN "The quantity is 30"
ELSE "The quantity is under 30"
END
FROM OrderDetails;
|
The following SQL will order the customers by City.
However, if City is NULL, then order by Country:
O seguinte SQL ordenará os clientes por cidade.
No entanto, se a cidade for NULL, ordene por país:
SELECT CustomerName, City, Country
FROM Customers
ORDER BY
(CASE
WHEN City IS NULL THEN Country
ELSE City
END);
|
If the first character of a department number is a division in the organization, then a CASE expression can be used to list the full name of the division to which
each employee belongs:
Se o primeiro caractere de um número de departamento for uma divisão na organização, uma expressão CASE pode ser usada para listar o nome completo da divisão à
qual cada funcionário pertence:
SELECT EMPNO, LASTNAME,
CASE SUBSTR(WORKDEPT,1,1)
WHEN 'A' THEN 'Administration'
WHEN 'B' THEN 'Human Resources'
WHEN 'C' THEN 'Accounting'
WHEN 'D' THEN 'Design'
WHEN 'E' THEN 'Operations'
END
FROM EMPLOYEE;
|
The number of years of education are used in the EMPLOYEE table to give the education level.
A CASE expression can be used to group these and to show the level of education.
O número de anos de educação é usado na tabela EMPLOYEE para fornecer o nível de educação.
Uma expressão CASE pode ser usada para agrupá-los e mostrar o nível de educação.
SELECT EMPNO, FIRSTNME, MIDINIT, LASTNAME,
CASE
WHEN EDLEVEL < 15 THEN 'SECONDARY'
WHEN EDLEVEL < 19 THEN 'COLLEGE'
ELSE 'POST GRADUATE'
END
FROM EMPLOYEE
|
Another interesting example of CASE statement usage is in protecting from division by 0 errors.
For example, the following code finds the employees who earn more than 25% of their income from commission, but who are not fully paid on commission:
Outro exemplo interessante de uso da instrução CASE é a proteção contra a divisão por 0 erros.
Por exemplo, o código a seguir encontra os funcionários que ganham mais de 25% de sua receita de comissão, mas que não são totalmente pagos pela comissão:
SELECT EMPNO, WORKDEPT, SALARY+COMM FROM EMPLOYEE
WHERE (CASE WHEN SALARY=0 THEN NULL
ELSE COMM/SALARY
END) > 0.25;
|
The following CASE expressions are the same:
As seguintes expressões CASE são iguais:
SELECT LASTNAME,
CASE
WHEN LASTNAME = 'Haas' THEN 'President'
...
SELECT LASTNAME,
CASE LASTNAME
WHEN 'Haas' THEN 'President'
...
|
DB2 Database - Banco de dados DB2:
Below is a selection from the "Employee" table in the DB2 database.
Abaixo está uma seleção da tabela "Funcionário" no banco de dados DB2.
| Employeeid |
Employeename |
workdepartment |
Age |
Country |
City |
| 7001 | Robert | ADM | 25 | India | Chennai |
| 7002 | Jancy | HUM | 35 | America | Newyork |
| 7003 | Brian | OPE | 40 | China | |
| 7004 | Phil | DES | 50 | America | Boston |
| 7005 | Carmen | ADM | 47 | Russia | |
| 7006 | Helen | OPE | 39 | England | London |
Example 1 - Exemplo 1:
Assume that in the "Employee" table the first character of a department number represents the division in the organization.
Use a CASE expression to list the full name of the division to which each employee belongs.
Suponha que na tabela "Funcionário" o primeiro caractere de um número de departamento represente a divisão na organização.
Use uma expressão CASE para listar o nome completo da divisão à qual cada funcionário pertence.
SELECT Employeeid, Employeename,
CASE SUBSTR(workdepartment,1,1)
WHEN 'A' THEN 'Administration'
WHEN 'H' THEN 'Human Resources'
WHEN 'D' THEN 'Design'
WHEN 'O' THEN 'Operations'
END AS "Department"
FROM Employee;
|
Result - Resultado:
| Employeeid |
Employeename |
Department |
| 7001 | Robert | Administration |
| 7002 | Jancy | Human Resources |
| 7003 | Brian | Operations |
| 7004 | Phil | Design |
| 7005 | Carmen | Administration |
| 7006 | Helen | Operations |
Example 2 - Exemplo 2:
The following SQL statement will order the employee by City.
However, if City is NULL, then order by Country:
A seguinte instrução SQL ordenará o funcionário por cidade.
No entanto, se a cidade for NULL, ordene por país:
SELECT Employeeid, Employeename, City, Country
FROM Employee
ORDER BY
(CASE
WHEN City IS NULL THEN Country
ELSE City
END);
|
Result - Resultado:
| Employeeid |
Employeename |
City |
Country |
| 7004 | Phil | Boston | America |
| 7001 | Robert | Chennai | India |
| 7006 | Helen | London | England |
| 7002 | Jancy | Newyork | America |
| 7003 | Brian | | China |
| 7005 | Carmen | | Russia |
Veja também:
|