SQL select all if parameter is null else return specific item

前端 未结 6 1440
终归单人心
终归单人心 2020-12-03 05:29

Is there a way to write the following script so that it returns all products if the ProductID variable is null ? And return a specific product when the product it is not nul

相关标签:
6条回答
  • 2020-12-03 06:06

    Try this

    DECLARE @productID INT = NULL
    
    SELECT 
        ProductID,
        ProductName,
        ProductDesc 
    FROM
        product 
    WHERE 
        ProductID = isnull(@productID,ProductID)
    
    0 讨论(0)
  • 2020-12-03 06:09

    Performance is a incredible better when using CASE statement:

    SELECT ProductID, ProductName,ProductDesc 
    FROM product 
    WHERE ProductID = CASE WHEN @productID IS NULL THEN ProductID ELSE @productID END
    

    ISNULL() prevents the optimizer using an index on that column.

    0 讨论(0)
  • 2020-12-03 06:13

    Use case statement:

    SELECT ProductID, ProductName,ProductDesc 
    FROM product 
    WHERE ProductID = CASE WHEN @productID IS NULL THEN ProductID ELSE @productID END
    

    Or IIF() function if you’re using SQL Server 2012:

    SELECT ProductID, ProductName,ProductDesc 
    FROM product 
    WHERE ProductID =IIF(@productID IS NULL, ProductID, @productID )
    
    0 讨论(0)
  • 2020-12-03 06:23
    SELECT
        ProductID,
        ProductName,
        ProductDesc 
    FROM
        product 
    WHERE
        ProductID = CASE WHEN @productID IS NULL THEN ProductID ELSE @productID END
    
    0 讨论(0)
  • 2020-12-03 06:24

    Since "" is not recognized as NULL I used value

    SELECT ProductID, ProductName,ProductDesc 
    FROM product 
    WHERE ProductID =IIF(@productID =1, ProductID, @productID )
    

    In my code:

     MyDataAdapter.SelectCommand.Parameters("@productID").Value = 1
    
    0 讨论(0)
  • 2020-12-03 06:25

    Why not just:

    DECLARE @productID INT = NULL
    
    SELECT ProductID, ProductName,ProductDesc 
    FROM   product 
    WHERE  ProductID = @productID
    OR     @productID IS NULL;
    

    Here a demo in SQLFiddle with NULL and a value for @productID

    0 讨论(0)
提交回复
热议问题