I need to write a query for my search page. My filters look like this:

@StartDateForColumn1 datetime,
@FinishDateForColumn1 datetime,
@StartDateForColumn2 datetime,
@FinishDateForColumn2 datetime,

All of them can be null. If so, I need all data:

select * from Table1

For example: If only@FinishDateForColumn1 is filled by the user, the query will be:

select * from Table1 where Column1<@FinishDateForColumn1 

So I don't want to write if-else for all conditions. Is there any other shortest way to write a query for this example? Maybe I need to use coalesce, but I don't know how to use it in this query.

有帮助吗?

解决方案 4

the following assumes that you don't have any dates outside the range 01/01/1971 and 31/12/2099.

select * 
from Table1 
where Column1< ISNULL(@FinishDateForColumn1,'31/Dec/2099') 
and Column1 > ISNULL(@StartDateForColumn1, '01/Jan/1971')
and Column2< ISNULL(@FinishDateForColumn2,'31/Dec/2099') 
and Column2 > ISNULL(@StartDateForColumn2, '01/Jan/1971')

其他提示

You can use coalesce, or isnull, in the following fashion

select * 
from Table1 
where Column1<= isnull(@FinishDateForColumn1, Column1)

NB. This does assume that your column1 data does not contain nulls.

You can do the following, which essentially ignores each parameter if it's null (by forcing the predicate criteria to be true) or uses it in the comparison if it is present.

select *
from Table 1
where
  Column1 < case when @StartDateForColumn1 is null then Column1 + 1 else @StartDateForColumn1 end
  and Column1 < case when @FinishDateForColumn1 is null then Column1 + 1 else @FinishDateForColumn1 end
  and ...

Something simple like using ISNULL would probably suffice.

WHERE 
    Column1 BETWEEN 
        ISNULL(@StartDateForColumn1, CAST('1 Jan 1753' as DATETIME)) 
        AND
        ISNULL(@EndDateForColumn1, CAST('1 Jan 9999' as DATETIME))
    AND
        Column2 BETWEEN 
            ISNULL(@StartDateForColumn2, CAST('1 Jan 1753' as DATETIME)) 
            AND
            ISNULL(@EndDateForColumn2, CAST('1 Jan 9999' as DATETIME))
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top