Lei*_*fel 12 oracle oracle-11g-r2 oracle-11g
LNNVL 是一个内置函数的预言机,它在条件评估为 FALSE 或 UNKNOWN 时返回 TRUE,并在条件评估为 TRUE 时返回 FALSE。我的问题是返回与真值条件相反的值而不是仅处理 NULL 值有什么好处?
例如,假设您有一个 Emp 表,其中包含可能包含空值的 StartCommission 和 CurrentCommission 列。以下仅返回值都不为 null 的行:
SELECT * FROM Emp WHERE StartCommission = CurrentCommission;
Run Code Online (Sandbox Code Playgroud)
如果您想包含其中任何一个佣金为空的行,您可以执行以下操作:
SELECT * FROM Emp WHERE StartCommission = CurrentCommission
OR StartCommission IS NULL OR CurrentCommission IS NULL;
Run Code Online (Sandbox Code Playgroud)
似乎存在一个函数来缩短此语法,但使用 LNNVL 会返回所有不相等的记录和所有具有空值的记录。
SELECT * FROM Emp WHERE LNNVL(StartCommission = CurrentCommission);
Run Code Online (Sandbox Code Playgroud)
添加 NOT 只返回没有空值的行。在我看来,这种情况下所需的功能是保持真条件为真,假条件为假,并使未知条件评估为真。我真的在这里创建了一个低用例吗?是否真的更可能想要将未知变为真、将真变为假、将假变为真?
create table emp (StartCommission Number(3,2), CurrentCommission Number(3,2));
insert into emp values (null,null);
insert into emp values (null,.1);
insert into emp values (.2,null);
insert into emp values (.3,.4);
Run Code Online (Sandbox Code Playgroud)
这么说吧,在我担任 DBA 和 PL/SQL 程序员的几年里,我还没有使用过 LNNVL。我偶尔使用过 NVL2(并且总是不得不查找哪一边是真的,哪一边不是)。到那时,从可读性的角度来看,最终使用 NVL、DECODE、CASE 等似乎更好,
或者,这是可行的,假设您对 Oracle 如何处理 NULL 和算术有很好的掌握,但此时,您还可以使用您的原始查询来提高可读性(并且执行计划也可能会受到更大的打击):
/* Return all rows where StartCommission is the same
* as Current Commission, or those rows who have a
* NULL in either (including both)
*/
SELECT *
FROM Emp
WHERE StartCommission = CurrentCommission
OR StartCommission + CurrentCommission IS NULL
-- NULL + NULL, or NULL + Number is always NULL; hence return either
-- those records that are equal, or have a combined total of NULL
-- (either or both fields will be NULL).
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2248 次 |
最近记录: |