1

我发现我的 SQL 2008 R2 数据库如果在搜索中使用 COALESCE 功能确实很困难。

代码:

where 
    i.id_categ = COALESCE(@id_categ, i.id_categ )
    and i.id_brand = COALESCE(@id_brand , i.id_brand )
    and i.id_model = COALESCE(@id_model , i.id_model )
    and i.id_type = COALESCE(@id_karoseria, i.id_type )
    and i.id_fuel = COALESCE(@id_palivo, i.id_fuel )
    and (i.year between @year_from and @year_to)
    and (i.price between @price_from and @price_to)

动态变量:

ALTER PROCEDURE [dbo].[spInzeratSelect]
     @id_categ int = null,
     @id_brand int = null,
     @id_model int = null,
     @id_fuel int = null,
     @id_type int = null,

搜索应该在有或没有这些变量的情况下工作。

基准:

  with COALESCE = Total Execution Time: 3582
  without COALESCE conditions = Total Execution Time: 13

你知道区别...

是否有一个很好的解决方案如何忽略 COALESCE 并使用不同的方法创建动态 SQL 选择?

谢谢。

4

1 回答 1

2

t在您非常具体的情况下,您应该使用以下模式替换所有COALESCE 搜索参数:

 AND ( (@id_brand IS NULL) OR (i.id_brand = @id_brand) )

ETC

该参数在执行之前被评估为文字,因此以这种方式执行此操作会使条件可调整。这在功能上等同于您的查询,除非您首先检查文字值,如果它实际上是 null,则可以对其进行优化。

编辑:显然这也是@Joe Stefanelli 链接中推荐的方法。我最初是从 Erland Sommerskog 挖来的。

EDIT2:我也总是忘记提及OPTION (RECOMPILE)

于 2011-04-12T16:49:17.803 回答