Reputation: 11125
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'.
Upvotes: 4
Views: 14127
Reputation: 10968
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
Upvotes: 6
Reputation: 6543
If you not need to check inbetween string then you can do trick like below :
SELECT column1, column2
FROM whatever
WHERE @SearchTerm LIKE
CASE @locationType
WHEN 'location' THEN account_location
WHEN 'area' THEN Area
WHEN 'division' THEN xxx_location_division
END
Or you can do like :
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)
Upvotes: 0