If-else statement in DB2/400

若如初见. 提交于 2021-02-20 19:09:32

问题


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

回答1:


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



回答2:


SELECT ABC, DEF,
CASE WHEN (substring(GHI,1,4)) IS 'SOTH' THEN 'J' ELSE 'N' END as SOTH
WHERE ABC like 'ABC%'
GROUP BY ABC,DEF,GHI


来源:https://stackoverflow.com/questions/34899015/if-else-statement-in-db2-400

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!