没有EXEC的SQL动态查询

时间:2014-08-13 14:41:21

标签: sql dynamicquery dynamic-queries

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

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执行?

谢谢!

3 个答案:

答案 0 :(得分:1)

使用null值可以替代。

例如:

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

但是,如果过滤许多列,性能可能会受到影响。请看Catch-all queries

答案 1 :(得分:0)

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

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

答案 2 :(得分: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