表:
ID AppType AppSubType Factor
1 SC CD 1.0000000000
2 SC CD 2.0000000000
3 SC NULL 3.0000000000
4 SC NULL 4.0000000000
查询:
declare @ast varchar(10)
set @ast = null
select *
from tbl
where AppType = 'SC' and AppSubType = ISNULL(@ast, AppSubType)
结果:
ID AppType AppSubType Factor
1 SC CD 1.0000000000
2 SC CD 2.0000000000
问题:
此查询不应该返回所有 4 条记录而不仅仅是前 2 条记录吗?
最佳答案
显然@ast是null,Isnull会将null与其他值交换,所以你不应该期望@ast不为null。如果您的 AppSubType 为 null ,则结果变为 null 但 AppSubType=null
并不意味着因为 AppSubType is null
为 true。因为 null 不是一个值,所以它不能与 equal 一起使用。
对于您的预期结果,此代码将起作用。
declare @ast varchar(10)
set @ast = null
select *
from tbl
where AppType = 'SC' and (AppSubType = ISNULL(@ast, AppSubType) Or AppSubType is null)
关于sql - 在 where 子句中使用 ISNULL 不会返回具有 NULL 字段的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19629171/