基于下拉列表中的多个值搜索表的存储过程

时间:2017-04-11 10:54:31

标签: sql sql-server sql-server-2008-r2

我有三个不同的值,例如

第一类下拉列表

第二类下拉列表

年度下拉列表

我必须根据下拉值搜索产品表,它应根据下拉列表中的任何一个或所有下拉列表选择值来过滤搜索。

我们假设我在产品表中有以下字段

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

如何最有效地编写存储过程,以便我无法处理所选的三个值中的任何一个。我想避免存储过程中的两个if语句

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搜索中创建动态查询

3 个答案:

答案 0 :(得分:2)

它被称为Dynamic Search Conditions。我建议你阅读Erland Sommarskog的这篇优秀文章。他解释了几种方法,如果你不使用动态SQL,为什么需要OPTION(RECOMPILE)

很少注意到。

使用前缀sp_命名存储过程是bad practice

我更喜欢传递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。

答案 1 :(得分: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

答案 2 :(得分: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