CASE é uma função complexa que possui dois formatos: o formato simples e o de pesquisa. Em qualquer formato, CASE retorna um valor, o resultado do qual controla o caminho do processo subseqüente.
Ambos os formatos de CASE retornam um valor, dependendo de um conjunto de regras definidas em cláusulas WHEN.
No formato simple-when, source_value é comparado com cada test_value até que seja localizada uma correspondência.O resultado da função CASE é o valor do result_value correspondente.O tipo de dados de source_value deve, portanto, ser comparável ao tipo de dados de cada test_value.
A função CASE deve ter pelo menos um WHEN. ELSE é opcional. A expressão ELSE padrão é NULL. Uma expressão CASE é delimitada por END. Os valores de teste não precisam ser valores literais.
A versão da cláusula de pesquisa é semelhante, mas possui flexibilidade adicional de permitir que vários valores diferentes sejam testados.
DECLARE CurrentMonth CHAR; DECLARE MonthText CHAR; SET CurrentMonth = SUBSTRING(InputBody.Invoice.InvoiceDate FROM 6 FOR 2); SET MonthText = CASE CurrentMonth WHEN '01' THEN 'January' WHEN '02' THEN 'February' WHEN '03' THEN 'March' WHEN '04' THEN 'April' WHEN '05' THEN 'May' WHEN '06' THEN 'June' ELSE 'Second half of year' END
DECLARE CurrentMonth CHAR; DECLARE MonthText CHAR; SET CurrentMonth = SUBSTRING(InputBody.Invoice.InvoiceDate FROM 6 FOR 2); SET MonthText = CASE WHEN Month = '01' THEN 'January' WHEN Month = '02' THEN 'February' WHEN Month = '03' THEN 'March' WHEN Month = '04' THEN 'April' WHEN Month = '05' THEN 'May' WHEN Month = '06' THEN 'June' ELSE 'Second half of year' END
DECLARE CurrentMonth CHAR; DECLARE CurrentYear CHAR; DECLARE MonthText CHAR; SET CurrentMonth = SUBSTRING(InputBody.Invoice.InvoiceDate FROM 6 FOR 2); SET CurrentYear = SUBSTRING(InputBody.Invoice.InvoiceDate FROM 1 FOR 4); SET MonthText = CASE WHEN CurrentMonth = '01' THEN 'January' WHEN CurrentMonth = '02' THEN 'February' WHEN CurrentMonth = '03' THEN 'March' WHEN CurrentYear = '2000' THEN 'A month in the Year 2000' WHEN CurrentYear = '2001' THEN 'A month in the Year 2001' ELSE 'Not first three months of any year or a month in the Year 2000 or 2001' END;