Chris Chris - 5 months ago 9
MySQL Question

How to use an user variables in MySQL LIKE clause?

I am trying to setup a few simple SQL scripts to help with some short term DB administration.
As such, I'm setting up variables to try to make it easier to reuse these scripts.

The problem I'm having is specifically with the LIKE clause.

SET @email = 'test@test.com';

SELECT email from `user` WHERE email LIKE '%@email%';


So I want to have it finding results based on the email SET in the variable. The query works if I manually enter the email into the LIKE clause.

How can I get the LIKE clause to work with the user variable?

UPDATE:
@dems's answer works for this simple case, but I'm having trouble with a more complex query.

SET @email = 'test@test.com';

SELECT project.projectno, project.projectname, login.username,
CONCAT(login.firstname, ' ', login.lastname), projectuser.title
FROM projectuser
INNER JOIN login ON projectuser.uid = login.uid
LEFT JOIN project ON projectuser.pid = project.pid
WHERE login.username LIKE CONCAT ('%', @email, '%')


Gives me the error "FUNCTION mydb.CONCAT does not exist"

The query works without the CONCAT():

SET @email = 'test@test.com';

SELECT project.projectno, project.projectname, login.username,
CONCAT(login.firstname, ' ', login.lastname), projectuser.title
FROM projectuser
INNER JOIN login ON projectuser.uid = login.uid
LEFT JOIN project ON projectuser.pid = project.pid
WHERE login.username LIKE @email

Answer
SET @email = 'test@test.com';

SELECT email from `user` WHERE email LIKE CONCAT('%', @email, '%');
Comments