2017-04-11 41 views
1

多個值,我有三個下具有不同的值,如存儲過程基於從下拉

第一類下拉

類別兩個下拉

年下拉

我要搜索表搜索基於下拉值的產品表,它應根據下拉列表或所有下拉選定值中的任何一個過濾搜索結果。

讓我們說,我有以下領域的產品表

ProductID 
ProductName 
ProductCatOne 
ProductCatTwo 
Description 
Image 
.... 
.... 

如何寫一個存儲過程,使我不能處理任何選擇的三個值的最有效的方式。我想避免兩個many如果存儲過程語句

ALTER PROCEDURE [dbo].[sp_SearchProduct] 
    @ProductID int, 
    @ProductCatOne int, 
    @ProductCatTwo int 
AS 
BEGIN 
SET NOCOUNT ON; 

If @ProductID > 0 THEN 

END IF 


END 
MS SQL Server的

存儲過程我不知道如何創建動態查詢SP FR這裏面搜索

回答

2

這就是所謂的Dynamic Search Conditions 。我建議你閱讀Erland Sommarskog的這篇優秀文章。他解釋了幾種實現方法,以及如果不使用動態SQL,爲什麼需要OPTION(RECOMPILE),如下例所示。

幾個筆記。

這是bad practice來命名您的存儲過程的前綴sp_

我傾向於通過NULL值而不是0來指示應忽略此參數。 0值可以是搜索的有效值。

ALTER PROCEDURE [dbo].[SearchProduct] 
    @ProductID int, 
    @ProductCatOne int, 
    @ProductCatTwo int 
AS 
BEGIN 
    SET NOCOUNT ON; 

    SELECT 
     ... 
    FROM Products 
    WHERE 
     (ID = @ProductID OR @ProductID IS NULL) 
     AND (ProductCatOne = @ProductCatOne OR @ProductCatOne IS NULL) 
     AND (ProductCatTwo = @ProductCatTwo OR @ProductCatTwo IS NULL) 
    OPTION(RECOMPILE); 

END 

此代碼假定列IDProductCatOneProductCatTwo不能有NULL值。

+0

我正好找這個..否則,我最終會做很多,如果條件。 SQL Server 2008提供了'OPTION(RECOMPILE)' – Learning

+0

是的,從SQL Server 2008開始就可以使用'OPTION(RECOMPILE)'(確保它是)。確保你已經應用了服務包。詳情請參閱Erland的文章。 –

+0

我所有的值都是'Int'類型,但我可以通過空值爲非選定的下拉 – Learning

1
ALTER PROCEDURE [dbo].[sp_SearchProduct] 
    @ProductID int, 
    @ProductCatOne int, 
    @ProductCatTwo int 
AS 
BEGIN 
SET NOCOUNT ON; 

    IF @ProductID ='' 
    SET @ProductID=NULL 

    IF @ProductCatOne ='' 
    SET @ProductCatOne=NULL 

    IF @ProductCatTwo ='' 
    SET @ProductCatTwo=NULL 

    SELECT * 
    FROM Product 
    WHERE ID = COALESCE (@ProductID,ID) 
      AND ProductCatOne =COALESCE (@ProductID,ProductCatOne) 
      AND ProductCatTwo=COALESCE (@ProductID,ProductCatTwo) 

END 
1
ALTER PROCEDURE [dbo].[SearchProduct] 
    @ProductID int, 
    @ProductName int, 
    @ProductCatOne int 
AS 
BEGIN 
    SET NOCOUNT ON; 

    SELECT 
     ... 
    FROM Products 
    WHERE 
    (Case When @ProductID <> 'ALL' Then ProductID Else @ProductID End) in(@ProductID) And 
    (Case When @ProductName <> 'ALL' Then ProductName Else @ProductName End) in(@ProductName) And 
    (Case When @ProductCatOne <> 'ALL' Then ProductCatOne Else @ProductCatOne End) in(@ProductCatOne) 


END