如何使用like运算符编写mysql存储过程

时间:2013-04-09 07:55:32

标签: mysql sql stored-procedures

以下是我的代码:

     DELIMITER $$

     CREATE DEFINER=`root`@`localhost` PROCEDURE `employee_with_asset`(IN name     VARCHAR(250))
     BEGIN
     SELECT a.Asset_code,a.name as name1,a.type,a.description,`purchase date`,
    `amc availability`,`amc renewal`,`employee Id`,b.Name FROM `asset_details` a,
     employee b WHERE  b.Name LIKE '%' + @name + '%' and a.`assigned to`=b.`employee Id`;
     END

在LIKE附近显示错误。如何解决它。

3 个答案:

答案 0 :(得分:19)

mysql中的串联是使用CONCAT()

完成的
LIKE CONCAT('%', @name , '%')

完整声明

DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `employee_with_asset`
(
    IN _name     VARCHAR(250)
)
BEGIN
    SELECT  a.Asset_code,
            a.name as name1,
            a.type,
            a.description,
            `purchase date`,
            `amc availability`,
            `amc renewal`,
            `employee Id`,
            b.Name 
    FROM    `asset_details` a
            INNER JOIN employee b 
                ON a.`assigned to` = b.`employee Id`
    WHERE   b.Name LIKE CONCAT('%', _name , '%');
END $$
DELIMITER ;

答案 1 :(得分:0)

John Woo的答案是正确的,但是如果你不使用utf8_general_ci集合,你必须在WHERE子句之后(如果你有多个条件,在每个条件之后)转换集合,就像你比较的列的集合一样像这样

... WHERE name LIKE CONCAT('%', @name , '%') COLLATE utf8_unicode_ci

或多个条件

... WHERE name LIKE CONCAT('%', @name , '%') COLLATE utf8_unicode_ci
OR job LIKE CONCAT('%', @name , '%') COLLATE utf8_unicode_ci ...

答案 2 :(得分:0)

PHP:

$keyword = $_POST['keyword'];
$response = "call user_search('%$keyword%');";

Mysql:

....where user.name like @keyword;