如何改写"DISTINCT FROM"和"NOT DISTINCT FROM"? [英] How to rewrite IS DISTINCT FROM and IS NOT DISTINCT FROM?
问题描述
如何在不支持它们的SQL实现(例如Microsoft SQL Server 2008R2)中重写包含标准IS DISTINCT FROM
和IS NOT DISTINCT FROM
运算符的表达式?
How do you rewrite expressions containing the standard IS DISTINCT FROM
and IS NOT DISTINCT FROM
operators in SQL implementations such as Microsoft SQL Server 2008R2 that do not support them?
推荐答案
IS DISTINCT FROM
谓词是作为SQL:1999的功能T151引入的,其可读性为IS NOT DISTINCT FROM
的添加是作为SQL:2003的功能T152的.这些谓词的目的是确保比较两个值的结果是 True 或 False ,从不 Unknown .
The IS DISTINCT FROM
predicate was introduced as feature T151 of SQL:1999, and its readable negation, IS NOT DISTINCT FROM
, was added as feature T152 of SQL:2003. The purpose of these predicates is to guarantee that the result of comparing two values is either True or False, never Unknown.
这些谓词可与任何可比较的类型(包括行,数组和多集)一起使用,从而使其难以精确模拟.但是,SQL Server不支持这些类型中的大多数,因此我们可以通过检查null参数/操作数来取得相当大的进步:
These predicates work with any comparable type (including rows, arrays and multisets) making it rather complicated to emulate them exactly. However, SQL Server doesn't support most of these types, so we can get pretty far by checking for null arguments/operands:
-
a IS DISTINCT FROM b
可以重写为:
((a <> b OR a IS NULL OR b IS NULL) AND NOT (a IS NULL AND b IS NULL))
a IS NOT DISTINCT FROM b
可以重写为:
a IS NOT DISTINCT FROM b
can be rewritten as:
(NOT (a <> b OR a IS NULL OR b IS NULL) OR (a IS NULL AND b IS NULL))
您自己的答案是错误的,因为它没有考虑FALSE OR NULL
评估为未知.例如,NULL IS DISTINCT FROM NULL
应该计算为 False .同样,1 IS NOT DISTINCT FROM NULL
应评估为 False .在这两种情况下,您的表达式都会产生 Unknown .
Your own answer is incorrect as it fails to consider that FALSE OR NULL
evaluates to Unknown. For example, NULL IS DISTINCT FROM NULL
should evaluate to False. Similarly, 1 IS NOT DISTINCT FROM NULL
should evaluate to False. In both cases, your expressions yield Unknown.
这篇关于如何改写"DISTINCT FROM"和"NOT DISTINCT FROM"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!