SQL Oracle 中的 if(condition, then, else)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1428402/
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 03:37:50  来源:igfitidea点击:

if(condition, then, else) in Oracle

sqloracleplsqlconditional-operator

提问by ModeEngage

MySQL/MSSQL has a neat little inline if function you can use within queries to detect null values, as shown below.

MySQL/MSSQL 有一个简洁的内联 if 函数,您可以在查询中使用它来检测空值,如下所示。

SELECT

...

foo.a_field AS "a_field",
SELECT if(foo.bar is null, 0, foo.bar) AS "bar",
foo.a_field AS "a_field",

...

The problem I'm running into now is that this code is not safe to run on an Oracle database, as it seems not to support this inline if syntax.

我现在遇到的问题是这段代码在 Oracle 数据库上运行不安全,因为它似乎不支持这种内联 if 语法。

Is there an equivalent in Oracle?

Oracle 中是否有等价物?

回答by David Andres

To supplement the rest of the answers here, which deal primarily with NULL values and COALESCE/NVL/NVL2:

补充此处的其余答案,主要处理 NULL 值和 COALESCE/NVL/NVL2:

SELECT *
FROM TheTable
WHERE field1 = CASE field2 WHEN 0 THEN 'abc' WHEN 1 THEN 'def' ELSE '' END

CASE statements are not as succinct, obviously, but they are geared towards flexibility. This is particularly useful when your conditions are not based on NULL-ness.

显然,CASE 语句没有那么简洁,但它们是面向灵活性的。当您的条件不基于 NULL 性时,这特别有用。

回答by Tony Andrews

Use the standard COALESCE function:

使用标准 COALESCE 函数:

SELECT COALESCE(foo.bar, 0) as "bar", ...

Or use Oracle's own NVL function that does the same.

或者使用 Oracle 自己的 NVL 函数来做同样的事情。

回答by OMG Ponies

You want to use NVL, or NVL2

您想使用NVLNVL2

NVL(t.column, 0)
NVL2( string1, value_if_NOT_null, value_if_null )

回答by Eric Petroelje

Yup, NVLshould do the trick.

是的,NVL应该可以解决问题。

回答by SquareCog

You want the nvl function: nvl(foo.bar, 0)

你想要 nvl 函数: nvl(foo.bar, 0)

Oracle does support various ifs and cases as well.

Oracle 也支持各种 if 和 case。

回答by tuinstoel

Just do nvl(foo.bar,0), you don't have to do

nvl(foo.bar,0),你不必做

(select nvl(foo.bar,0)...