MySQL:procedure, function, cursor,handler

Procedure & Function

Procedure 语法:

CREATE
    [DEFINER = { user | CURRENT_USER }]
    PROCEDURE sp_name ([proc_parameter[,...]])
    [characteristic ...] routine_body


proc_parameter:
    [ IN | OUT | INOUT ] param_name type

type:
    Any valid MySQL data type

characteristic:
    COMMENT 'string'
  | LANGUAGE SQL
  | [NOT] DETERMINISTIC
  | { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA }
  | SQL SECURITY { DEFINER | INVOKER }

begin
    Valid SQL routine statement
end;

 

Function 语法:

CREATE
    [DEFINER = { user | CURRENT_USER }]
    FUNCTION sp_name ([func_parameter[,...]])
    RETURNS type
    [characteristic ...] routine_body

func_parameter:
    param_name type

type:
    Any valid MySQL data type

characteristic:
    COMMENT 'string'
  | LANGUAGE SQL
  | [NOT] DETERMINISTIC
  | { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA }
  | SQL SECURITY { DEFINER | INVOKER }

begin
    Valid SQL routine statement
end;

官网关于 procedure, function相关文档:

  FAQ:http://dev.mysql.com/doc/refman/5.6/en/faqs-stored-procs.html

  语法说明:http://dev.mysql.com/doc/refman/5.6/en/create-procedure.html

 

Cursor

Cursor官方文档:http://dev.mysql.com/doc/refman/5.6/en/cursors.html

在遍历时,mysql中的3种循环方式(loop, while, repeat)都可以使用。官方文档中给了 loop 方式的deamo。

在使用cursor时要注意:

1)declare cursor之前不能有任何的除了declare以外的操作,也就是之前只能有变量声明。

2)declar cursor 之后不能有任何变量的声明,可以声明异常处理 handler。

3)cursor 只能在procedure, function中。

4)fetch into var1, var2。这里的var名不能与 declare cursor时select 中的列名一样。如果一样会fetch 到NULL。例如下面deamon中的 metric ==> m 。

其它的deamon:http://www.mysqltutorial.org/mysql-cursor/

 

Handler

在什么样的条件下,做什么样的处理。例如当发生异常时,该怎么做。

相关文档:http://dev.mysql.com/doc/refman/5.6/en/declare-handler.html

在下面的deamon中就有declare continue handler NOT FOUND 、declare continue handler SQLSTATE 等。

 

Demo

 

 

 

Debugger Tool

http://mydebugger.com/quick_start.php

 

 

 

上面 的两个procedure,在使用debugger调试时,只需要在main中写直接调用 就可以了。

 

posted @ 2016-12-01 21:24  乐享程序员  阅读(817)  评论(0编辑  收藏  举报