Search code examples
sqlsearchswitch-statementcasesql-like

SQL Case and LIKE in where clause


I have been breaking my head over this hope it's possible

declare @locationType varchar(50);
declare @SearchTerm NVARCHAR(100);

SELECT column1, column2
FROM whatever
WHERE
CASE @locationType
    WHEN 'location' THEN account_location LIKE @SearchTerm
    WHEN 'area' THEN Area LIKE @SearchTerm
    WHEN 'division' THEN xxx_location_division LIKE @SearchTerm
END

I copied the code form another related post here.

I get the error:

Incorrect syntax near the keyword 'LIKE'.


Solution

  • declare @locationType varchar(50);
    declare @SearchTerm NVARCHAR(100);
    
    SELECT column1, column2
    FROM whatever
    WHERE
       (@locationType = 'location' AND account_location LIKE @SearchTerm)
    OR
       (@locationType = 'area' AND Area LIKE @SearchTerm)
    OR
       (@locationType = 'division' AND xxx_location_division LIKE @SearchTerm)
    

    Make sure that @SearchTerm starts with/end with % -> or use '%' + @SearchTerm + '%'.

    More info on LIKE operator.

    --- Update ----

    SELECT column1, column2
    FROM whatever
    WHERE
    (
      CASE @locationType
         WHEN 'location' THEN account_location
         WHEN 'area' THEN Area
         WHEN 'division' THEN xxx_location_division
      END
    ) LIKE @SearchTerm