MYSQL存储过程
-
创建
CREATE PROCEDURE 存储过程名([参数])
BEGIN
存储过程体
END;
- 参数:IN/OUT/INOUT 参数名 参数类型
eg:
CREATE PROCEDURE myprocedure1() BEGIN SELECT "hello myprocedure1"; END;
-
调用
CALL 存储过程名([参数])
eg:
CALL myprocedure1();
-
显示存储过程
SHOW PROCEDURE STATUS [WHERE db=‘数据库名’ and name like ‘%存储过程名%’ …]
eg:
SHOW PROCEDURE STATUS WHERE db='test' and name LIKE '%my%';
-
显示存储过程的源码
SHOW CREATE PROCEDURE 存储过程名
eg:
SHOW CREATE PROCEDURE myprocedure1;
-
删除存储过程
DROP PROCEDURE 存储过程名
eg:
DROP PROCEDURE myprocedure1;
变量
-
变量定义
DECLARE 变量名[,变量名…] 变量类型 [DEFAULT 默认值];
-
变量赋值
SET 变量名 = 表达式值;
eg:
CREATE PROCEDURE myprocedure1(IN a int,IN b int,OUT sum int)
BEGIN
SET sum = a+b;
END;
CREATE PROCEDURE myprocedure2()
BEGIN
DECLARE username1 varchar(16);
SET username1='张三';
SELECT username1;
END;
CALL myprocedure1(1,2,@sum);
SELECT @sum;
CALL myprocedure2();
流程控制
-
IF
IF 判断 THEN
…
ELSEIF 判断 THEN
…
ELSE
…
END IF;
eg:
CREATE PROCEDURE myprocedure3(IN num int) BEGIN IF num<0 THEN SELECT '负数'; ELSEIF num=0 THEN SELECT '不是正数也不是负数'; ELSE SELECT '正数'; END IF; END; CALL myprocedure3(1);
-
CASE
CASE变量
WHEN 值 THEN
…
WHEN 值 THEN
…
ELSE
…
END CASE;
eg:
CREATE PROCEDURE myprocedure4(IN num int) BEGIN CASE num -- 条件开始 WHEN 1 THEN SELECT '数值是 1'; WHEN 2 THEN SELECT '数值是 2'; ELSE SELECT '不是 1 也不是 2'; END CASE; END; CALL myprocedure4(3);
-
WHILE
WHILE 判断 DO
…
END WHILE;
eg:
CREATE PROCEDURE myprocedure5(OUT sum int) BEGIN DECLARE i int DEFAULT 0; SET sum=0; WHILE i<10 DO SET i=i+1; SET sum=sum+i; END WHILE; END; CALL myprocedure5(@tmp); SELECT @tmp;