SQL Server : check if variable is Empty or NULL for WHERE clause

后端 未结 5 1345
萌比男神i
萌比男神i 2020-12-23 20:41

When searching for a list of products, the @SearchType parameter is optional. If @SearchType is empty or NULL then it should return al

5条回答
  •  天命终不由人
    2020-12-23 21:02

    If you don't want to pass the parameter when you don't want to search, then you should make the parameter optional instead of assuming that '' and NULL are the same thing.

    ALTER PROCEDURE [dbo].[psProducts] 
    (
      @SearchType varchar(50) = NULL
    )
    AS
    BEGIN
      SET NOCOUNT ON;
    
      SELECT P.[ProductId]
      ,P.[ProductName]
      ,P.[ProductPrice]
      ,P.[Type]
      FROM dbo.[Product] AS P
      WHERE p.[Type] = COALESCE(NULLIF(@SearchType, ''), p.[Type]);
    END
    GO
    

    Now if you pass NULL, an empty string (''), or leave out the parameter, the where clause will essentially be ignored.

提交回复
热议问题