3

The goal

Concatenate a parameter with a % operator of LIKE using MySQL.

The problem

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.

The scenario

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?

4

3 回答 3

4

通常实际传入的不是我们想的那样。

检查参数:

  • 不为空
  • 没有前导或尾随空格

试试这个来防范上述情况:

WHERE people.LOGIN LIKE CONCAT(TRIM(IFNULL(expression, '')), '%')
于 2013-09-18T13:23:45.713 回答
1

您需要使用准备好的语句

使用查询创建一个字符串,并使用准备好的语句执行它。像这样的东西-

SET @query = CONCAT('SELECT * FROM table1 WHERE column1 LIKE ''', expression, '%''');
PREPARE stmt FROM @query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
于 2013-09-18T13:19:51.730 回答
0

您可以使用定位。例子:

位置(pParamText,column1)> 0

于 2015-02-16T22:08:37.123 回答