MySQL存储过程

定义

在一些语言中,有一个概念叫过程'procedure',和函数'function'sql

过程:封装了若干条语句,调用时,封装体执行。没有返回值的函数 函数:有一个返回值的"过程"数据库

存储过程:将过程存储在数据库中。函数

命令

查看已有的过程:show procedure status
删除存储过程: drop procedure if exists procedure_name
调用存储过程:   call procedure()

语法

1.基础结构

create procedure procedureName()
begin
  -- 执行的sql
end$

2.变量

存储过程当中,能够用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 $

repeat循环

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)$
相关文章
相关标签/搜索