我在 SQL 查询中使用了以下形式的过滤器:
declare @filter1 as Int
declare @filter2 as Int
declare @filter3 as Int
set @filter1 = 39
set @filter2 = 84
set @filter3 = null
select *
from Table1 T1
inner join Table2 T2 on T1.Id = T2.T1_Id
inner join Table3 T3 on T2.Id = T3.T2_Id
where T1.Id = isnull(@filter1, T1.Id)
and T2.Id = isnull(@filter2, T2.Id)
and T3.Id = isnull(@filter3, T3.Id)
但是,如果您有大量信息,SQL Server 就不会以正确的方式找出查询,也不会使用数据库中的正确索引。
我建议使用以下形式的查询:
declare @filter1 as int
declare @filter2 as int
declare @filter3 as int
set @filter1 = 39
set @filter2 = 84
set @filter3 = null
--Dynamic Query Begin
declare @query as varchar(max)
set @query = '
select *
from Table1 T1
inner join Table2 T2 on T1.Id = T2.T1_Id
inner join Table3 T3 on T2.Id = T3.T2_Id
where T1.Id = T1.Id '
if @filter1 is not null
set @query = @query + ' and T1.Id = ' + convert(varchar(10),@filter1)
if @filter2 is not null
set @query = @query + ' and T2.Id = ' + convert(varchar(10),@filter2)
if @filter3 is not null
set @query = @query + ' and T3.Id = ' + convert(varchar(10),@filter3)
exec sp_executesql @query
--Dynamic Query End