在一些语言中,有一个概念叫过程'procedure',和函数'function'sql
过程:封装了若干条语句,调用时,封装体执行。没有返回值的函数 函数:有一个返回值的"过程"数据库
存储过程:将过程存储在数据库中。函数
查看已有的过程:show procedure status 删除存储过程: drop procedure if exists procedure_name 调用存储过程: call procedure()
create procedure procedureName() begin -- 执行的sql end$
存储过程当中,能够用declare声明变量 格式 declare 变量名 变量类型 [default 默认值]code
DELIMITER $; create procedure p1() begin declare age int default 18; declare height int default 180; select concat(age, '::', height) from dual; end$
DELIMITER $; create procedure p2() begin declare age int default 18; declare height int default 180; set age:= age+1; select age from dual; end$
DELIMITER $; create procedure p3() begin declare age int default 18; if age> 18 then select '已成年' from dual; else select '未成年' from dual; end if; end$
存储过程能够传递参数 格式: [in| out| inout] 参数名 参数类型io
DELIMITER $; create procedure p4(age int) begin if age> 18 then select '已成年' from dual; elseif age = 18 then select '正好成年' from dual; else select '未成年' from dual; end if; end$
DELIMITER $; CREATE PROCEDURE p5(n INT) BEGIN DECLARE total INT DEFAULT 0; DECLARE num INT DEFAULT 0; WHILE num < n DO SET num := num + 1; SET total := total + num; END WHILE; SELECT total FROM DUAL; END$
in 输入function
out 输出基础
inout 既能输入也能输出变量
DELIMITER $; CREATE PROCEDURE p7(IN n INT, OUT total INT) BEGIN DECLARE num INT DEFAULT 0; SET total := 0; WHILE num < n DO SET num := num + 1; SET total := total + num; END WHILE; END$ CALL p7(100, @total)$ SELECT @total FROM DUAL$
DELIMITER $; CREATE PROCEDURE p8(INOUT age INT) BEGIN SET age := age + 10; END$ SET @currage = 18$ CALL p8(@currage)$ SELECT @currage $
DELIMITER $; CREATE PROCEDURE p10(n INT) BEGIN DECLARE total INT DEFAULT 0; DECLARE num INT DEFAULT 0; REPEAT SET total := total + num; SET num := num +1; UNTIL num > n END REPEAT; SELECT total FROM DUAL; END$ CALL p10(100)$