MySQL SP不返回结果?可变问题?

时间:2014-01-11 06:46:32

标签: mysql

一个简单的问题:我已将数据库从MSSQL移到MySQL,我现在正在转换存储过程。但是,这个在执行时似乎没有正常运行(我可以创建它,但是当我运行它时我得不到结果):

DELIMITER $$

CREATE PROCEDURE `Employee_GetAll`(
IN community_id int,
IN search varchar(255)
)
BEGIN

select e.*, er.name as rolename, er.access_level as accesslevel from Employee e
inner join Employee_Role er on e.employee_role = er.id
where e.community_id = community_id
and (firstname like ('%' + search + '%') or lastname like ('%' + search + '%'));

END

所以,我可以创建它,但是当我运行它时没有给出结果。如果我运行此代码......

select e.*, er.name as rolename, er.access_level as accesslevel from Employee e
inner join Employee_Role er on e.employee_role = er.id
where e.community_id = 1
and (firstname like ('%do%') or lastname like ('%do%'));

...然后运行正常。那么,我是否在使用SEARCH变量做错了什么?我是MySQL的新手,并尝试稍微改进它。

此致

鲍勃

1 个答案:

答案 0 :(得分:0)

一些问题:

  1. 不要为参数指定与列名相同的名称
  2. 使用CONCAT()LIKE
  3. 构建模式
  4. 由于它是一个声明程序,因此您不需要使用BEGIN...END阻止并更改DELIMITER
  5. 这就是说这样试试

    CREATE PROCEDURE `Employee_GetAll`(
      IN _community_id INT,
      IN _search VARCHAR(255)
    )
    SELECT e.*, er.name AS rolename, er.access_level AS accesslevel 
     FROM Employee e JOIN Employee_Role er 
       ON e.employee_role = er.id
     WHERE e.community_id = _community_id
       AND (firstname LIKE CONCAT('%', _search, '%') OR 
            lastname  LIKE CONCAT('%', _search, '%'));
    

    这是 SQLFiddle 演示