Search code examples
sqlsql-servert-sqlcasesql-like

Using of CASE in WHERE clause to evaluate empty parameters


Is there a better way to obtain the following?

DECLARE @Desc VARCHAR(200) = ''

SELECT [id],
       [Desc],
       [Col1],
       [Col2]
FROM [dbo].[tbl]
WHERE [Desc] LIKE CASE
                WHEN @Desc LIKE ''
                     THEN [Desc]
                     ELSE '%'+ @Desc +'%'
                END

This allows to return all values if the parameter is not defined (@Desc='') or return a subset of values (@Desc='test').


Solution

  • Use OR Operator instead of Case

    DECLARE @Desc VARCHAR(200) = ''
    
    SELECT [id],
           [Desc],
           [Col1],
           [Col2]
    FROM [dbo].[tbl]
    WHERE 
        (
            ISNULL(@Desc,'')=''
        )
        OR
        (
            ISNULL(@Desc,'')<>''
            AND
            [Desc] LIKE '%'+ @Desc +'%'
        )
    

    Execution Plan Difference using Both Logics

    Using Case

    enter image description here

    Using Or

    enter image description here