I am trying to create a stored procedure where, depending on a parameter not being an empty string, an AND condition should be added to the query. If the parameter is an empty string, the AND condition should not be added at all. I want the matching to use LIKE not "=", as in:
DECLARE @searchstring VARCHAR(50);
SET @searchstring = 'hang up';
SELECT *
FROM ContactLog
WHERE CREATED_DATE > '2020-01-01'
AND Brief_Statement LIKE '%' + CASE
WHEN @searchstring != ''
THEN @searchstring
ELSE Brief_Statement
END + '%'
AND Log_Type = 'L';
SET @searchstring = '';
SELECT *
FROM ContactLog
WHERE CREATED_DATE > '2020-01-01'
-- in this case, since @searchString is empty, I'd like to eliminate this next condition altogether
AND Brief_Statement LIKE '%' + CASE
WHEN @searchstring != ''
THEN @searchstring
ELSE Brief_Statement
END + '%'
AND Log_Type = 'L'
I know that if I am using "=" instead of LIKE, I can do this...
SET @searchstring = '';
SELECT TOP 10 *
FROM ContactLog
WHERE CREATED_DATE > '2020-01-01'
AND Brief_Statement = CASE
WHEN @searchstring != ''
THEN @searchstring
ELSE Brief_Statement
END
AND Log_Type = 'L'
But I am not sure of the effect of doing this with LIKE and would like the query to be as efficient as possible.
What is a good way to do this?