数据库21/10/20

存储过程

存储过程的参数

MySQL存储过程的参数共有三种:IN/OUT/INOUT

1.IN输入参数
输入参数———在调用存储过程中传递数据给存储过程的参数(在调用的过程必须给一个实际的值)

创建存储过程,向数据表中添加数据

CREATE PROCEDURE pro_test2(IN stu_num INT,IN stu_name VARCHAR(20),
in stu_age int,in stu_phone varchar(13),in stu_qq varchar(11),in stu_sex char(3))
BEGIN
 INSERT INTO stu(stu_num,stu_name,stu_age,stu_phone,stu_qq,stu_sex)
 VALUES(stu_num,stu_name,stu_age,stu_phone,stu_qq,stu_sex);
END;

CALL pro_test2(7,'莉莉',21,13204771151,2261771456,'女');

2.OUT输出参数
输出参数———将存储过程中产生的数据返回给过程调用者,相当于java的返回值,不同的是有个存储过程可以多个不同的参数

创建存储过程,根据学生学号查询学生姓名

CREATE PROCEDURE pro_test3(IN snum int,out sname varchar(10))
begin
  SELECT stu_name into sname from stu where stu_num = snum;
end;

set @n = '';
call pro_test3(5,@n);
select @n from DUAL;

3.INOUT建议少用

创建存储过程,根据学生学号查询学生姓名

create PROCEDURE pro_test4(INOUT s varchar(10))
begin
  select stu_name into s from stu where stu_num = s;
end;

set @s = '3';
call pro_test4(@s);
SELECT @s from DUAL;

存储过程的流程控制

在存储过程中支持流程控制语句用于实现逻辑的控制

1.分支语句

  • if-then-else
 -- 单分支语句
    if 条件 then
    SQL语句
    end if;
 -- 双分支语句
    if 条件 then
    SQL语句1
    else
    SQL语句2
    end if;

创建存储过程,若参数输入的是1,则添加一条班级信息
若参数输入的是2,则添加一条学生信息

CREATE PROCEDURE pro_test5(in num int)
begin
  if num=1 THEN
  INSERT INTO class(class_id,class_name,sid)
  VALUES(5,'计算机',1);
  ELSE
  INSERT INTO stu(stu_name,stu_age,stu_sex)
  VALUES('图图',5,'男');
  end if;
end;

call pro_test5(1);
  • case
create procedure pro_test(in a int)
begin
   case a
   when 1 then
   -- SQL1
   when 2 then
   -- SQL2
   else
   -- SQL(如果都不匹配,执行该语句)
   end case;
end;

2.循环语句

  • while

创建一个存储过程,添加参数指定格式的班级信息,即参数决定添加几条信息

CREATE PROCEDURE pro_test6(in num int)
BEGIN
  DECLARE i int; -- 定义一个局部参数
  set i=0;
  while i<num DO
  INSERT INTO class(class_id,class_name,sid)
  VALUES(6+i,CONCAT('java',i),4);
  set i=i+1;
  end while;
END;

call pro_test6(2);
  • repeat

上述问题

create procedure pro_test7(in num int)
begin
  declare i int;
  set i = 1;
  repeat
  INSERT INTO class(class_id,class_name,sid)
  VALUES(8+i,CONCAT('Pythen',i),1+i);
  set i=i+1;
  until i>num end repeat;
end;

call pro_test7(3);
  • loop

上述问题

create procedure pro_test7(in num int)
begin
  declare i int;
  set i = 1;
  repeat
  INSERT INTO class(class_id,class_name,sid)
  VALUES(8+i,CONCAT('Pythen',i),1+i);
  set i=i+1;
  until i>num end repeat;
end;

call pro_test7(3);
posted @ 2021-10-20 18:44  想吃坚果  阅读(46)  评论(0)    收藏  举报