cancel
Showing results for 
Search instead for 
Did you mean: 

difference between if...then...else and case when

t1950
Participant
2,784
select ...,
  ( if table1.column1 > '' then table1.bin_location else table2.bin_location end if ) as bin1,
  ( Case
    when table1.column1 > '' then table1.bin_location
    else table2.bin_location
    End ) as bin2,
  ... 
From ...

I'm using SA 16, EBF 1761. The IF statement does NOT return a value. I don't remember if it was '' or null. The CASE statement returns what I expect, i.e. it returns the values I'm expecting. why the different behavior.

Accepted Solutions (1)

Accepted Solutions (1)

Breck_Carter
Participant

It is a bug feature 🙂

Here's an excerpt from The Book:

3.10.1 IF and CASE Expressions

The IF and CASE keywords can be used to create expressions as well as to code IF-THEN-ELSE and CASE statements. The statements are discussed in Chapter 8, “Packaging,” and the expressions are described here. <if_expression> ::= IF <boolean_expression> THEN <expression> [ ELSE <expression> ] ENDIF

The IF expression evaluates the <boolean_expression> to determine if it is TRUE, FALSE, or UNKNOWN. If the <boolean_expression> result is TRUE, the THEN <expression> is returned as the result of the IF. If the <boolean_expression> is FALSE, the ELSE <expression> is returned as the result of the IF. If there is no ELSE <expression>, or if the <boolean_expression> is UNKNOWN, then NULL is returned as the result of the IF. ... The CASE expression comes in two forms: <case_expression> ::= <basic_case_expression> | <searched_case_expression> <basic_case_expression> ::= CASE <basic_expression> WHEN <expression> THEN <expression> { WHEN <expression> THEN <expression> } [ ELSE <expression> ] END ... The second form of the CASE expression is more flexible; you are not limited to the implicit equals “=” operator, nor are you limited to a single CASE comparison value on the left side of all the WHEN comparisons.

<searched_case_expression> ::= CASE WHEN <boolean_expression> THEN <expression> { WHEN <boolean_expression> THEN <expression> } [ ELSE <expression> ] END

Each WHEN <boolean_expression> is evaluated, in turn, to result in a TRUE, FALSE, or UNKNOWN result. As soon as a TRUE result is encountered, the search is over; the corresponding THEN <expression> is evaluated and returned as the result of the CASE. If all the results are FALSE or UNKNOWN, then the ELSE <expression> is evaluated and returned; if there is no ELSE <expression>, then NULL is returned.

Answers (0)