Use a variable in a WHERE clause with a LIKE predicate

To use a variable in a WHERE clause, you can concatenate the multicharacter wildcard operator % or the single character wildcard _ onto the variable to perform a fuzzy match.

WHERE u.UserName LIKE '%' + @myVariable + '%';

Here’s an example of it in use:

-- First let's define a variable with a default value
DECLARE @myVariable VARCHAR(64) = 'Karen'

-- Then we concatenate the % wildcard onto the variable
SELECT
	u.Id,
	u.FirstName,
	c.Content,
	c.SubmittedAt
FROM [dbo].[sqlstr_Users] u
	INNER JOIN [dbo].[sqlstr_Complaints] c ON u.Id = c.UserId
WHERE u.UserName LIKE '%' + @myVariable + '%';
Eric
Eric

Code guy.

Articles: 18

Leave a Reply

Your email address will not be published. Required fields are marked *