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 = '[email protected]'; 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 = '[email protected]'; 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 = '[email protected]'; 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
It may be as simple as LIKE '%%[%3]%%' being [%3] the input variable. Show activity on this post. I ran into a similar problem. I needed to use just a small piece of a URL saved in my database where the front and ends were irrelevant.
User variables are written as @ var_name , where the variable name var_name consists of alphanumeric characters, . , _ , and $ . A user variable name can contain other characters if you quote it as a string or identifier (for example, @'my-var' , @"my-var" , or @`my-var` ).
Mysql also supports the concept of User-defined variables, which allows passing of a value from one statement to another. A user-defined variable in Mysql is written as @var_name where, var_name is the name of the variable and can consist of alphanumeric characters, ., _, and $.
The syntax for assigning a value to a SQL variable within a SELECT query is @ var_name := value , where var_name is the variable name and value is a value that you're retrieving. The variable may be used in subsequent queries wherever an expression is allowed, such as in a WHERE clause or in an INSERT statement.
SET @email = '[email protected]'; SELECT email from `user` WHERE email LIKE CONCAT('%', @email, '%');
Works without concat():
LIKE '%{$var}%'
(Mysql version 5.+)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With