2011-04-12 80 views
1

我發現如果在搜索範圍內使用SQL 2008 R2數據庫,我們確實正在努力使用COALESCE函數。如何在沒有COALESCE的情況下創建動態WHERE選擇

CODE:

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選擇?

謝謝。

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

的參數作爲執行前的文字評價,這樣做:

+2

查看Gail Shaw的[Catch-all queries](http://sqlinthewild.co.za/index.php/2009/03/19/catch-all-queries/)的博文。 – 2011-04-12 15:43:34

回答

2

錫您非常具體情況下,你應該用下面的方式取代所有的COALESCE搜索參數這種方式使得條件可變。 這與您的查詢在功能上等效,除非您首先檢查字面值,如果是,實際上可以將其優化爲空值。

編輯:顯然這是@Joe Stefanelli鏈接中推薦的方法。我原本是從Erland Sommerskog那裏挖來的。

編輯2:我也經常忘記提及OPTION (RECOMPILE)

相關問題