为什么 NVL 总是评估第二个参数

发布于 2024-08-17 19:14:47 字数 428 浏览 13 评论 0原文

有谁知道,为什么Oracle的NVL(和NVL2)函数总是评估第二个参数,即使第一个参数不是NULL

简单测试:

CREATE FUNCTION nvl_test RETURN NUMBER AS
BEGIN
  dbms_output.put_line('Called');
  RETURN 1;
END nvl_test;

SELECT NVL( 0, nvl_test ) FROM Dual

返回 0,但也打印 Called

nvl_test 已被调用,即使结果被忽略,因为第一个参数不是 NULL

Does anyone know, why Oracle's NVL (and NVL2) function always evaluate the second parameter, even if the first parameter is not NULL?

Simple test:

CREATE FUNCTION nvl_test RETURN NUMBER AS
BEGIN
  dbms_output.put_line('Called');
  RETURN 1;
END nvl_test;

SELECT NVL( 0, nvl_test ) FROM dual

returns 0, but also prints Called.

nvl_test has been called, even though the result is ignored since first parameter is not NULL.

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

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

发布评论

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

评论(4

原野 2024-08-24 19:14:47

一直都是这样,因此 Oracle 必须保持这种方式以保持向后兼容。

使用 COALESCE 来获取短路行为。

It's always been that way, so Oracle has to keep it that way to remain backwards compatible.

Use COALESCE instead to get the short-circuit behaviour.

一笑百媚生 2024-08-24 19:14:47

在这篇文章中,Tom Kyte 确认了 decodecase 短路,但没有确认 nvl,但他没有给出理由或说明原因。只是声明为:

http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:926029357278#14932880517348

所以在你的情况下你应该使用 decodecase 而不是 nvl 如果查询中将调用昂贵的函数。

Here is a post where Tom Kyte confirms that decode and case short circuit but not nvl but he doesn't give justification or documentation for why. Just states it to be:

http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:926029357278#14932880517348

So in your case you should use decode or case instead of nvl if an expensive function will be called in your query.

嘿看小鸭子会跑 2024-08-24 19:14:47

一般来说,在调用函数之前评估第二个参数是有意义的,因为通常这就是函数的调用方式:评估函数的所有参数并将评估值发送到函数。

然而,对于像 NVL 这样非常常见的系统函数,我认为 PL/SQL 可以进行优化,将函数调用视为特殊情况。但也许这比听起来更困难(对我来说),因为我确信 Oracle 的开发人员会想到这种优化。

In general, it would make sense that the second parameter is evaluated before calling the function, because in general that is how functions are called: all arguments to the function are evaluated and the evaluated values are sent to the function.

However, in the case of a very common system function like NVL, I would have thought PL/SQL could optimise, treating the function call as a special case. But perhaps that is more difficult than it sounds (to me), as I'm sure this optimisation would have occurred to the developers of Oracle.

口干舌燥 2024-08-24 19:14:47

它们显然没有短路,但我在 Oracle 文档中找不到任何参考资料。

查看此讨论:http://forums.oracle.com/forums/thread .jspa?messageID=3478040

They are obviously not short-circuiting, but I can't find any references in Oracle documentation.

Check out this discussion: http://forums.oracle.com/forums/thread.jspa?messageID=3478040

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