Oracle 中的 if(条件, then, else)

发布于 2024-08-05 06:24:15 字数 285 浏览 4 评论 0原文

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",

...

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

Oracle 中有类似的吗?

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

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.

Is there an equivalent in Oracle?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

隔岸观火 2024-08-12 06:24:15

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

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

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

To supplement the rest of the answers here, which deal primarily with NULL values and 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.

网白 2024-08-12 06:24:15

使用标准 COALESCE 函数:

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

或者使用 Oracle 自己的 NVL 函数来执行相同的操作。

Use the standard COALESCE function:

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

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

木格 2024-08-12 06:24:15

您想要使用 NVLNVL2

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

You want to use NVL, or NVL2

NVL(t.column, 0)
NVL2( string1, value_if_NOT_null, value_if_null )
慕烟庭风 2024-08-12 06:24:15

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

Yup, NVL should do the trick.

ゞ记忆︶ㄣ 2024-08-12 06:24:15

您需要 nvl 函数: nvl(foo.bar, 0)

Oracle 也支持各种 if 和 case。

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

Oracle does support various ifs and cases as well.

記柔刀 2024-08-12 06:24:15

只需执行 nvl(foo.bar,0) 即可,无需执行

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

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

(select nvl(foo.bar,0)... 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文