If-else statement in DB2/400

ehh picture ehh · Jan 20, 2016 · Viewed 29.6k times · Source

I am trying to run an SQL that contains if-else statement in AS400 but it doesn't work. I am creating a View using i Series Navigator in order to run it.

SELECT IF FIELD1 IS NOT NULL THEN 'AAA' ELSE 'BBB' END IF
FROM LIB.TABLE1

The error I am getting is:

SQL State: 42601
Vendor Code: -199
Message: [SQL0199] Keyword IS not expected. Valid tokens: , FROM INTO. Cause . . 

I tried without writing is null but instead

SELECT IF FIELD1 ='' THEN 'AAA' ELSE 'BBB' END IF
    FROM LIB.TABLE1

then I get the following error:

SQL State: 42601
Vendor Code: -104
Message: [SQL0104] Token = was not valid. Valid tokens: , FROM INTO. Cause . . . . . :   A syntax error was detected at token =.  Token = is not a

Answer

Lukasz Szozda picture Lukasz Szozda · Jan 20, 2016

Use CASE expression instead:

SELECT CASE WHEN FIELD1 IS NOT NULL THEN 'AAA' ELSE 'BBB' END 
FROM LIB.TABLE1;

IF is control-flow construct:

IF condition THEN 
   SELECT ...
ELSE 
   SELECT ...
END IF