سؤال

Table:

ID     AppType     AppSubType   Factor
1   SC  CD      1.0000000000
2   SC  CD      2.0000000000
3   SC  NULL    3.0000000000
4   SC  NULL    4.0000000000

Query:

declare @ast varchar(10)

set @ast = null

select *
from tbl
where AppType = 'SC' and AppSubType = ISNULL(@ast, AppSubType)

Result:

ID  AppType AppSubType  Factor
1   SC  CD  1.0000000000
2   SC  CD  2.0000000000

Question:

Shouldn't this query return all 4 records and not just the first 2?

هل كانت مفيدة؟

المحلول

Abviously @ast is null and Isnull would exchange null with other value, so you shouldn't expect @ast to be not null. If your AppSubType is null , so the result become null but AppSubType=null doesn't mean because AppSubType is null is true. Because null is not a value so it cant work with equal. for your expected result this code will work.

declare @ast varchar(10)

set @ast = null

select *
from tbl
where AppType = 'SC' and (AppSubType = ISNULL(@ast, AppSubType) Or AppSubType is null)

نصائح أخرى

You can write a case condition in where clause as:

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

Please understand the behavior of ISNULL explained in below blog.

the very first expression in the isnull function is a column value or the expression of some result.

ISNULL Explored in Detail

The code looks like a search functionality. If the value is not given then replace them with whatever is there in database and if given pull only those records which are matched.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top