您可以使用if
語句來控制執行哪些語句,但不能用它來刪除部分查詢。
不以這種方式構建的一個原因是,查詢的執行計劃會因輸入而有所不同,因此每次都必須創建新的執行計劃並且無法重新使用。
有不同的方式來處理這個問題,喜歡用isnull
函數的值進行比較,以本身如果varaible爲null:
AND c.UserFld1 = isnull(@color, c.UserFld1)
或檢查空比較之前:
AND (@coor is null or c.UserFld1 = @color)
您始終可以在查詢周圍放置if
語句,這會爲您提供查詢的兩個版本,每個版本的計劃比運行查詢時檢查該值的計劃略好。有時值得重複的代碼:
If @color is not Null Begin
Select b.ItemKey, a.CatKey, a.ParentKey, a.CatName, g.ItemID, c.UserFld1, c.UserFld3, c.UserFld5, f.UOMID, e.SizeValue
From dbo.timWebCategory a Inner JOIN
dbo.timWebCategoryItem b ON a.CatKey = b.CatKey Inner JOIN
mas500_app.dbo.timItem c ON b.ItemKey = c.ItemKey Inner JOIN
dbo.cpsIMItemDetails d ON c.ItemKey = d.ItemKey Inner JOIN
dbo.timItemSize e ON c.ItemKey = e.ItemKey Left JOIN
dbo.timVolumeUOM f ON e.VolUOMKey = f.VolUOMKey Left JOIN
mas500_app.dbo.vWebItem g ON c.ItemKey = g.ItemKey
Where a.Catkey = @Key
AND d.IntFlg = 1
AND c.UserFld1 = @color
Order By f.UOMID, e.SizeValue
End Else Begin
Select b.ItemKey, a.CatKey, a.ParentKey, a.CatName, g.ItemID, c.UserFld1, c.UserFld3, c.UserFld5, f.UOMID, e.SizeValue
From dbo.timWebCategory a Inner JOIN
dbo.timWebCategoryItem b ON a.CatKey = b.CatKey Inner JOIN
mas500_app.dbo.timItem c ON b.ItemKey = c.ItemKey Inner JOIN
dbo.cpsIMItemDetails d ON c.ItemKey = d.ItemKey Inner JOIN
dbo.timItemSize e ON c.ItemKey = e.ItemKey Left JOIN
dbo.timVolumeUOM f ON e.VolUOMKey = f.VolUOMKey Left JOIN
mas500_app.dbo.vWebItem g ON c.ItemKey = g.ItemKey
Where a.Catkey = @Key
AND d.IntFlg = 1
Order By f.UOMID, e.SizeValue
End
(謂詞演算)的一般規則是:如果x然後y'在邏輯上等於'(NOT x)或y'。或者更正式地說,'p - > q =〜p v q'。 – Josh