日期:2014-05-16  浏览次数:20821 次

MySQL:在命令行下创建 MySQL 存储过程问题
ref:http://rubyqiu.php.blog.163.com/blog/static/8614152320081010103521768/

本文代码在 MySQL 5.0.41-community-nt 下运行通过。

编写了个统计网站访问情况(user agent)的 MySQL 存储过程。就是下面的这段 SQL 代码。

drop procedure if exists pr_stat_agent;

-- call pr_stat_agent ('2008-07-17', '2008-07-18')

create procedure pr_stat_agent
(
   pi_date_from  date
  ,pi_date_to    date
)
begin
   -- check input
   if (pi_date_from is null) then
      set pi_date_from = current_date();
   end if;

   if (pi_date_to is null) then
      set pi_date_to = pi_date_from;
   end if;

   set pi_date_to = date_add(pi_date_from, interval 1 day);

   -- stat
   select agent, count(*) as cnt
     from apache_log
    where request_time >= pi_date_from
      and request_time <  pi_date_to
    group by agent
    order by cnt desc;
end;
我在 EMS SQL Manager 2005 for MySQL 这个 MySQL 图形客户端下可以顺利运行。但是在 SQLyog MySQL GUI v5.02 这个客户端就会出错。最后找到原因是没有设置好 delimiter 的问题。默认情况下,delimiter “;” 用于向 MySQL 提交查询语句。在存储过程中每个 SQL 语句的结尾都有个 “;”,如果这时候,每逢 “;” 就向 MySQL 提交的话,当然会出问题了。于是更改 MySQL 的 delimiter,上面 MySQL 存储过程就编程这样子了:

delimiter //;     -- 改变 MySQL delimiter 为:“//”

drop procedure if exists pr_stat_agent //

-- call pr_stat_agent ('2008-07-17', '2008-07-18')

create procedure pr_stat_agent
(
   pi_date_from  date
  ,pi_date_to    date
)
begin
   -- check input
   if (pi_date_from is null) then
      set pi_date_from = current_date();
   end if;

   if (pi_date_to is null) then
      set pi_date_to = pi_date_from;
   end if;

   set pi_date_to = date_add(pi_date_from, interval 1 day);

   -- stat
   select agent, count(*) as cnt
     from apache_log
    where request_time >= pi_date_from
      and request_time <  pi_date_to
    group by agent
    order by cnt desc;
end; //

delimiter ; //   -- 改回默认的 MySQL delimiter:“;”
当然,MySQL delimiter 符号是可以自由设定的,你可以用 “/” 或者“$$” 等。但是 MySQL 存储过程中比较常见的用法是 “//” 和 “$$”。上面的这段在 SQLyog 中的代码搬到 MySQL 命令客户端(MySQL Command Line Client)却不能执行。

mysql> delimiter //;     -- 改变 MySQL delimiter 为:“//”
mysql>
mysql> drop procedure if exists pr_stat_agent //
    ->
    -> -- call pr_stat_agent ('2008-07-17', '2008-07-18')
    ->
    -> create procedure pr_stat_agent
    -> (
    ->    pi_date_from  date
    ->   ,pi_date_to    date
    -> )
    -> begin
    ->    -- check input
    ->    if (pi_date_from is null) then
    ->       set pi_date_from = current_date();
    ->    end if;
    ->
    ->    if (pi_date_to is null) then
    ->       set pi_date_to = pi_date_fr