Concatenate a parameter with a % operator of LIKE using MySQL.
There's the following query on my database and it returns me the results very well:
SELECT people.LOGIN, people.EMAIL FROM people
WHERE people.LOGIN LIKE 'o%'
ORDER BY people.LOGIN ASC
LIMIT 10;
But I want to call this function using a Stored Procedure, and instead of use 'o%', I want to use '<myvariable>%' and I'm not managing to do this.
I've tried the following on my procedure:
BEGIN
SELECT people.EMAIL FROM people
WHERE people.LOGIN LIKE CONCAT(expression, '%')
ORDER BY people.LOGIN ASC
LIMIT 10;
END
The result? Empty. This query returns me nothing.
Someone has any idea to help me?
Often what actually gets passed in is not what we think.
Check that the parameter:
Try this to guard against the above:
WHERE people.LOGIN LIKE CONCAT(TRIM(IFNULL(expression, '')), '%')
You need to use prepared statements.
Create a string with a query, and execute it using prepared statements. Something like this -
SET @query = CONCAT('SELECT * FROM table1 WHERE column1 LIKE ''', expression, '%''');
PREPARE stmt FROM @query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
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