5

桌子:

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 条吗?

4

3 回答 3

4

显然 @ast 为 null 并且 Isnull 会将 null 与其他值交换,因此您不应期望 @ast 不为 null。如果您的 AppSubType 为 null ,则结果为 null 但AppSubType=null并不意味着因为AppSubType is null为真。因为 null 不是一个值,所以它不能与 equal 一起使用。对于您预期的结果,此代码将起作用。

declare @ast varchar(10)

set @ast = null

select *
from tbl
where AppType = 'SC' and (AppSubType = ISNULL(@ast, AppSubType) Or AppSubType is null)
于 2013-10-28T07:46:54.150 回答
0

您可以在 where 子句中编写 case 条件:

declare @ast varchar(10)

set @ast = null

select *
from tbl
where AppType = 'SC' and 1=
      case when isnull(@ast ,'') = '' and isnull(AppSubType ,'') = '' then 1
           when AppSubType = ISNULL(@ast, AppSubType) then 1 
           else 0
      end
于 2013-10-28T07:57:12.757 回答
0

请理解下面博客中解释的 ISNULL 行为。

isnull 函数中的第一个表达式是列值或某个结果的表达式。

ISNULL详解

该代码看起来像一个搜索功能。如果未给出该值,则将它们替换为数据库中的任何内容,如果给出,则仅提取匹配的那些记录。

于 2013-10-29T11:16:32.933 回答