Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If-else statement in DB2/400

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
like image 996
ehh Avatar asked Jan 20 '16 11:01

ehh


1 Answers

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
like image 143
Lukasz Szozda Avatar answered Oct 13 '22 09:10

Lukasz Szozda