1.存储过程和函数的区别在于函数必须有返回值,而存储过程没有,存储过程的参数可以使用IN、OUT、INOUT类型,而函数的参数只能是IN类型。
2.创建存储过程或者函数需要CREATE ROUTINE权限,修改或者删除存储过程或者函数需要ALTER ROUTINE权限,执行存储过程或者函数需要EXECUTE权限。
3.创建存储过程的语法为:
CREATE PROCEDURE sp_name([proc_parameter, ...])
[characteristic ...] routine_body
proc_parameter:
[IN | OUT | INOUT] param_name type
characteristic:
LANGUAGE SQL | [NOT] DETERMINISTIC | {CONTAINS SQL | NO SQL | READS SQL DATA | MODIFY SQL DATA} | SQL SECURITY {DEFINER | INVOKER} | COMMENT 'string'
type:
Any valid MySQL data type
routine_body:
Valid SQL procedure statement or statements
4.创建存储函数的语法为:
CREATE FUNCTION sp_name([func_parameter, ...])
RETURNS type
[characteristic ...] routine_body
func_parameter:
param_name type
characteristic:
LANGUAGE SQL | [NOT] DETERMINISTIC | {CONTAINS SQL | NO SQL | READS SQL DATA | MODIFY SQL DATA} | SQL SECURITY {DEFINER | INVOKER} | COMMENT 'string'
type:
Any valid MySQL data type
routine_body:
Valid SQL procedure statement or statements
5.修改存储过程或函数的语法为:
ALTER {PROCEDURE | FUNCTION} sp_name [characteristic ...]
characteristic:
{CONTAINS SQL | NO SQL | READS SQL DATA | MODIFY SQL DATA} | SQL SECURITY {DEFINER | INVOKER} | COMMENT 'string'
6.调用过程的语法为:
CALL sp_name([parameter, ...])
7.MySQL的存储过程和函数中允许包含DDL语句,也允许在存储过程中执行提交(Commit)或者回滚(Rollback),但是存储过程和函数中不允许执行LOAD DATA INFILE语句。此外,存储过程和函数中可以调用其他的过程或者函数。
8.示例:
CREATE PROCEDURE film_in_stock(IN p_film_id INT, IN p_store_id INT, OUT p_film_count INT)
READS SQL DATA
BEGIN
SELECT inventory_id
FROM inventory
WHERE film_id = p_film_id
AND store_id = p_store_id
AND inventory_in_stock(inventory_id);
SELECT FOUND_ROWS() INTO p_film_count;
END