1

具有动态过滤器的查询的当前替代方案是什么?例如:

SELECT cost
FROM tblData
WHERE Filter1 in (3,5,6,7)
AND Filter2 in (20,11,66,24)
AND Filter3 in (50,22,66,33)

等等...我可能没有Filter2、Filter1 或Filter3(取决于参数)。在我的真实场景中,我最多可以有 10 个过滤器。以上只是一个例子。

是否有任何新方法无需像文本一样构建此查询并使用 EXEC 执行?

谢谢!

4

3 回答 3

1

使用null值还有另一种选择。

例如:

WHERE (@filter Is Null OR table.column <> @filter)
  AND (@filter2 Is Null OR table.column2 <> @filter2)

但是,如果您对许多列进行过滤,则性能可能会受到影响。查看包罗万象的查询

于 2014-08-13T14:49:05.180 回答
0

我在 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
于 2014-08-13T15:23:26.947 回答
0

通过参数动态生成sql,然后尝试使用EXEC(@sql)

如果使用sqlserver2005,可以使用EXEC SP_EXECUTESQL @sql,SP_EXECUTESQL 更强

于 2014-08-13T14:51:53.507 回答