mysql 存储过程实例和基本语法
mysql 存储过程实例
DELIMITER $$
DROP PROCEDURE IF EXISTS getUserInfo $$
CREATE PROCEDURE getUserInfo(in date_day datetime)
--
-- 实例
-- 存储过程名为:getUserInfo
-- 参数为:date_day日期格式:2008-03-08
--
BEGIN
declare _userName varchar(12); -- 用户名
declare _chinese int ; -- 语文
declare _math int ; -- 数学
declare done int;
-- 定义游标
DECLARE rs_cursor CURSOR FOR SELECT username,chinese,math from userInfo where datediff(createDate, date_day)=0;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done=1;
-- 获取昨天的日期
if date_day is null then
set date_day = date_add(now(),interval -1 day);
end if;
open rs_cursor;
cursor_loop:loop
FETCH rs_cursor into _userName, _chinese, _math; -- 取数据
if done=1 then
leave cursor_loop;
end if;
-- 更新表
update infoSum set total=_chinese+_math where UserName=_userName;
end loop cursor_loop;
close rs_cursor;
END$$
DELIMITER ;
mysql存储过程基本语法
CREATE
[DEFINER = { user | CURRENT_USER }]
PROCEDURE sp_name ([proc_parameter[,...]])
[characteristic ...] routine_body
CREATE
[DEFINER = { user | CURRENT_USER }]
FUNCTION sp_name ([func_parameter[,...]])
RETURNS type
[characteristic ...] routine_body
proc_parameter:
[ IN | OUT | INOUT ] param_name type
func_parameter:
param_name type
type:
Any valid MySQL data type
characteristic:
LANGUAGE SQL
| [NOT] DETERMINISTIC
| { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA }
| SQL SECURITY { DEFINER | INVOKER }
| COMMENT 'string'
routine_body:
Valid SQL procedure statement
CREATE PROCEDURE and CREATE FUNCTION Syntax
例子:
DELIMITER $$
DROP FUNCTION IF EXISTS f_discount_price$$
CREATE FUNCTION f_discount_price
(normal_price NUMERIC(8,2))
RETURNS NUMERIC(8,2)
DETERMINISTIC
BEGIN
DECLARE discount_price NUMERIC(8,2);
IF (normal_price > 500) THEN
SET discount_price = normal_price * .8;
ELSEIF (normal_price >100) THEN
SET discount_price = normal_price * .9;
ELSE
SET discount_price = normal_price;
END IF;
RETURN(discount_price);
END$$
DELIMITER ;
触发器
触发器在INSERT、UPDATE或DELETE等DML语句修改数据库表时触发
触发器的典型应用场景是重要的业务逻辑、提高性能、监控表的修改等
触发器可以在DML语句执行前或后触发
DELIMITER $$
DROP TRIGGER sales_trigger$$
CREATE TRIGGER sales_trigger
BEFORE INSERT ON sales
FOR EACH ROW
BEGIN
IF NEW.sale_value > 500 THEN
SET NEW.free_shipping = 'Y';
ELSE
SET NEW.free_shipping = 'N';
END IF;
IF NEW.sale_value > 1000 THEN
SET NEW.discount = NEW.sale_value * .15;
ELSE
SET NEW.discount = 0;
END IF;
END$$
DELIMITER ;
MySQL存储过程的异常处理方法
mysql>
mysql> delimiter $$
mysql>
mysql> CREATE PROCEDURE myProc
-> (p_first_name VARCHAR(30),
-> p_last_name VARCHAR(30),
-> p_city VARCHAR(30),
-> p_description VARCHAR(30),
-> OUT p_sqlcode INT,
-> OUT p_status_message VARCHAR(100))
-> BEGIN
->
-> /* START Declare Conditions */
->
-> DECLARE duplicate_key CONDITION FOR 1062;
-> DECLARE foreign_key_violated CONDITION FOR 1216;
->
-> /* END Declare Conditions */
->
-> /* START Declare variables and cursors */
->
-> DECLARE l_manager_id INT;
->
-> DECLARE csr_mgr_id CURSOR FOR
-> SELECT id
-> FROM employee
-> WHERE first_name=p_first_name
-> AND last_name=p_last_name;
->
-> /* END Declare variables and cursors */
->
-> /* START Declare Exception Handlers */
->
-> DECLARE CONTINUE HANDLER FOR duplicate_key
-> BEGIN
-> SET p_sqlcode=1052;
-> SET p_status_message='Duplicate key error';
-> END;
->
-> DECLARE CONTINUE HANDLER FOR foreign_key_violated
-> BEGIN
-> SET p_sqlcode=1216;
-> SET p_status_message='Foreign key violated';
-> END;
->
-> DECLARE CONTINUE HANDLER FOR not FOUND
-> BEGIN
-> SET p_sqlcode=1329;
-> SET p_status_message='No record found';
-> END;
->
-> /* END Declare Exception Handlers */
->
-> /* START Execution */
->
-> SET p_sqlcode=0;
-> OPEN csr_mgr_id;
-> FETCH csr_mgr_id INTO l_manager_id;
->
-> IF p_sqlcode<>0 THEN /* Failed to get manager id*/
-> SET p_status_message=CONCAT(p_status_message,' when fetching manager id');
-> ELSE
-> INSERT INTO employee (first_name,id,city)
-> VALUES(p_first_name,l_manager_id,p_city);
->
-> IF p_sqlcode<>0 THEN /* Failed to insert new department */
-> SET p_status_message=CONCAT(p_status_message,
-> ' when inserting new department');
-> END IF;
-> END IF;
->
-> CLOSE csr_mgr_id;
->
-> /* END Execution */
->
-> END$$
Query OK, 0 rows affected (0.02 sec)
mysql>
mysql> delimiter ;
mysql> set @myCode = 0;
Query OK, 0 rows affected (0.00 sec)
mysql> set @myMessage = 0;
Query OK, 0 rows affected (0.00 sec)
mysql>
mysql> call myProc('Jason','Martin','New City','New Description',@myCode,@myMessage);
Query OK, 1 row affected (0.00 sec)
mysql>
mysql> select @myCode, @myMessage;
+---------+------------+
| @myCode | @myMessage |
+---------+------------+
| 0 | NULL |
+---------+------------+
1 row in set (0.00 sec)
mysql>
mysql> drop procedure myProc;
Query OK, 0 rows affected (0.00 sec)