CASE é uma função complexa que possui dois formatos; o formato simples e o de pesquisa. Em qualquer formato, CASE retorna um resultado, o valor do qual controla o caminho do processamento subseqüente.
>>-CASE--+-| simple-when-clause |---+---------------------------> '-| searched-when-clause |-' .-ELSE NULL---------------------. >--+-------------------------------+--END---------------------->< '-ELSE --expressão_de_resultado-' simple-when-clause |--source_value-------------------------------------------------> .-----------------------------------------------------. V | >----WHEN --valor_de_teste--THEN--+-valor_de_resultado-+-+------| '-NULL---------------' searched-when-clause .----------------------------------------------------------. V | |----WHEN --condição_de_procura--THEN--+-valor_de_resultado-+-+--| '-NULL---------------'
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 uma cláusula WHEN. A expressão 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.
O formato de pesquisa é semelhante, mas possui a flexibilidade adicional de permitir vários valores diferentes a serem 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;