问题
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