coalesce()
在任何数据库中,比较可空字段是否相等似乎是一种常见做法。例如,如果您要比较两个可为空的字符串字段,您可以使用where coalesce(tbl1.stringfield,'') = coalesce(tbl2.stringfield,'')
. 这是有效的,因为转换的空字符串在''
上下文中可以很好地转换为null
.
但是,如果您正在处理没有“空”等价物的日期或数字等数据类型怎么办?在 Teradata 中,如果您尝试where coalesce(tbl1.numberfield,'') = coalesce(tbl2.numberfield,'')
,如果其中一个字段不为空,则会收到数据类型不匹配错误。这是因为它试图将数字与空字符串进行比较。要让它工作,你必须使用where coalesce(tbl1.numberfield,0) = coalesce(tbl2.numberfield,0)
. 但是,如果 tbl1.numberfield 为 null 而 tbl2.numberfield 实际上包含 0 的值怎么办?WHERE 条件将返回 true,而实际上它应该返回 false,因为一个值为 null,另一个为 0。我能看到的唯一解决方法是这个非常笨拙的案例逻辑:
where case
when
(tbl1.numberfield is null and tbl2.numberfield is null) or
(tbl1.numberfield is not null and tbl2.numberfield is not null) or
tbl1.numberfield <> tbl2.numberfield
then 1
else 0
end = 1
并且认为如果允许将两个空值与一个简单的等号进行比较,那么所有这些都可以避免。