SQL DB2/400 中的 if-else 语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34899015/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 04:21:18  来源:igfitidea点击:

If-else statement in DB2/400

sqlviewibm-midrange

提问by ehh

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.

我正在尝试在 AS400 中运行包含 if-else 语句的 SQL,但它不起作用。我正在使用 i Series Navigator 创建一个视图以运行它。

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

回答by Lukasz Szozda

Use CASEexpression instead:

改用CASE表达式:

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

IFis control-flow construct:

IF是控制流结构:

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

回答by GuestPGM

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