delimiter的作用介绍(二)

2015-07-24 08:59:01 · 作者: · 浏览: 1
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:“;”

      
    1. -> //
    2. -> //
    3. -> //
    4. -> ;
    5. -> ;
    6. ->

    真是奇怪了!最后终于发现问题了,在 MySQL 命令行下运行 “delimiter //; ” 则 MySQL 的 delimiter 实际上是 “//;”,而不是我们所预想的 “//”。其实只要运行指令 “delimiter //” 就 OK 了。

    MySQL> delimiter // -- 末尾不要符号 “;”

      
    1. MySQL>
    2. MySQL> drop procedure if exists pr_stat_agent //
    3. Query OK, 0 rows affected (0.00 sec)
    4. MySQL>
    5. MySQL> -- call pr_stat_agent ('2008-07-17', '2008-07-18')
    6. MySQL>
    7. MySQL> create procedure pr_stat_agent
    8. -> (
    9. -> pi_date_from date
    10. -> ,pi_date_to date
    11. -> )
    12. -> begin
    13. -> -- check input
    14. -> if (pi_date_from is null) then
    15. -> set pi_date_from = current_date();
    16. -> end if;
    17. ->
    18. -> if (pi_date_to is null) then
    19. -> set pi_date_to = pi_date_from;
    20. -> end if;
    21. ->
    22. -> set pi_date_to = date_add(pi_date_from, interval 1 day);
    23. ->
    24. -> -- stat
    25. -> select agent, count(*) as cnt
    26. -> from apache_log
    27. -> where request_time >= pi_date_from
    28. -> and request_time < pi_date_to
    29. -> group by agent
    30. -> order by cnt desc;
    31. -> end; //
    32. Query OK, 0 rows affected (0.00 sec)
    33. MySQL>
    34. MySQL> delimiter ;

    末尾不要符号 “//”

      
    1. MySQL>

    顺带一提的是,我们可以在 MySQL 数据库中执行在文件中的 SQL 代码。例如,我把上面存储过程的代码放在文件 d:\pr_stat_agent.sql 中。可以运行下面的代码建立存储过程。

      
    1. MySQL> source d:\pr_stat_agent.sql
    2. Query OK, 0 rows affected (0.00 sec)
    3. Query OK, 0 rows affected (0.00 sec)

    source 指令的缩写形式是:“\.”

      
    1. MySQL> \. d:\pr_stat_agent.sql
    2. Query OK, 0 rows affected (0.00 sec)
    3. Query OK, 0 rows affected (0.00 sec)

    最后,可见 MySQL数据库的客户端工具在有些地方是各自为政,各有各的一套。