2012-06-19 39 views
0

我試圖從這個查詢中擠出一些性能,任何幫助將不勝感激,我唯一能做的就是在第二個語句中刪除順序爲它是由主鍵性能調優小T-SQL IF ELSE STATEment,運行數千次

--SET STATISTICS TIME ON 

DECLARE    
     @MasterAdGroupId Int = 3469476, 
     @IncludeDeleted Bit = 1, 
     @Deleted Bit = 0, 
     @IncludeDirty Bit= 0, 
     @Dirty Bit =1, 
     @IncludeDupes Bit=0, 
     @OrderByText Bit= 1, 
     @UseInDisplayNetworkOnly Bit=0 

BEGIN 

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED 
IF @OrderByText=1 
BEGIN 
    SELECT MasterKeywordId, Text, URL, MasterAdGroupId, mk.KeywordTemplateId, Dirty, mk.Deleted, Negative, Duplicate 
     FROM admanMasterKeyword_tbl mk 
INNER JOIN admanKeywordTemplate_tbl kt on kt.KeywordTemplateId = mk.KeywordTemplateId 
    WHERE MasterAdGroupId = @MasterAdGroupId 
     AND mk.Deleted = CASE WHEN @IncludeDeleted=0 THEN @Deleted ELSE mk.Deleted END 
     AND Dirty = CASE WHEN @IncludeDirty=0 THEN @Dirty ELSE Dirty END 
     AND Duplicate = CASE WHEN @IncludeDupes=1 THEN Duplicate ELSE 0 END 
     AND UseInDisplayNetwork = CASE WHEN @UseInDisplayNetworkOnly=1 THEN 1 ELSE UseInDisplayNetwork END 
    ORDER BY Text 
END 
ELSE 
BEGIN 
    SELECT MasterKeywordId, Text, URL, MasterAdGroupId, mk.KeywordTemplateId, Dirty, mk.Deleted, Negative, Duplicate 
     FROM admanMasterKeyword_tbl mk 
INNER JOIN admanKeywordTemplate_tbl kt on kt.KeywordTemplateId = mk.KeywordTemplateId 
    WHERE MasterAdGroupId = @MasterAdGroupId 
     AND mk.Deleted = CASE WHEN @IncludeDeleted=0 THEN @Deleted ELSE mk.Deleted END 
     AND Dirty = CASE WHEN @IncludeDirty=0 THEN @Dirty ELSE Dirty END 
     AND Duplicate = CASE WHEN @IncludeDupes=1 THEN Duplicate ELSE 0 END 
     AND UseInDisplayNetwork = CASE WHEN @UseInDisplayNetworkOnly=1 THEN 1 ELSE UseInDisplayNetwork END 
    ORDER BY MasterKeywordId 
END 

END 
+0

主鍵沒有暗示的順序,無論數據返回的順序如何。要調整這種類型的查詢,我會參考Erland Sommarskog關於動態搜索參數的權威性文章:http://www.sommarskog。 se/dyn-search.html –

回答

1

這不會改變任何東西的性能明智的排序,但如果你要在兩個查詢變化是它們的排序方式(我看不出任何差異)您可以在ORDER BY中放置一個CASE語句,而不必重複自己或者根本不需要重複IF語句:

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED 

    SELECT MasterKeywordId, Text, URL, MasterAdGroupId, mk.KeywordTemplateId, Dirty, mk.Deleted, Negative, Duplicate 
     FROM admanMasterKeyword_tbl mk 
INNER JOIN admanKeywordTemplate_tbl kt on kt.KeywordTemplateId = mk.KeywordTemplateId 
    WHERE MasterAdGroupId = @MasterAdGroupId 
     AND mk.Deleted = CASE WHEN @IncludeDeleted=0 THEN @Deleted ELSE mk.Deleted END 
     AND Dirty = CASE WHEN @IncludeDirty=0 THEN @Dirty ELSE Dirty END 
     AND Duplicate = CASE WHEN @IncludeDupes=1 THEN Duplicate ELSE 0 END 
     AND UseInDisplayNetwork = CASE WHEN @UseInDisplayNetworkOnly=1 THEN 1 ELSE UseInDisplayNetwork END 
    ORDER BY (CASE WHEN @OrderByText = 1 THEN Text ELSE MasterKeywordId END) 

該查詢的查詢計劃是什麼樣的?任何地方你可以創建索引?

+0

查詢計劃是一個聚集索引查找與另一個索引通過嵌套循環查找,因此它看起來很好 –

+0

您的代碼絕對看起來更乾淨,所以我會看看如果明天在辦公室, 謝謝 –