MySql教程

mysql-学习01 数据库存储过程操作

本文主要是介绍mysql-学习01 数据库存储过程操作,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

一、批量插入

1)for循环调用Dao中的单条插入方法

2)传一个List<Object>参数,使用Mybatis的批量插入 (foreach)

对于批量插入它的Mapper看起来向这样

CREATE DEFINER=`root`@`localhost` PROCEDURE `insert_exam`(in studentid0 int)
BEGIN
DECLARE examid0 int;
declare fromc0 int;
declare toc0 int;
declare type0 int;
declare diff0 int;
declare c0 int;
declare c1 int;
declare done int default false;
declare cur cursor for
select `fromchapterId`,`tochapterId`,`type`,`difficulty`,`count` from exam_rule;
declare continue handler for not found set done=true;
select count(*) into c1 from exam where studentid=studentid0;
if c1=0 then
insert into exam(studentid,fromtime,state) values(studentid0,now(),0);
select LAST_INSERT_ID() into examid0;

open cur;
fetch cur into fromc0,toc0,type0,diff0,c0;
while(not done) do
insert into exam_detail(`examid`,`questionid`,`answer`,`grade`)
select examid0 as examid,questionid,'' as answer,0 as grade
from questionbank where chapterId>=fromc0 and chapterId<=toc0 and type=type0 and difficulty=diff0 order by rand() limit c0;
fetch cur into fromc0,toc0,type0,diff0,c0;
end while;
close cur;
end if;

END

 

CREATE DEFINER=`root`@`localhost` PROCEDURE `insert_exams_class`(in classid0 int)
BEGIN
declare stuid int;
declare done int default false;
declare cur cursor for
select studentid from student where classid=classid0;
declare CONTINUE HANDLER for not found set done=true;

open cur;
FETCH cur into stuid;
while(not done) do
call insert_exam(stuid);
FETCH cur into stuid;
end while;
close cur;
END

二、解析字符串

1)使用聚合函数 count(),locate(),mid()等等

CREATE DEFINER=`root`@`localhost` PROCEDURE `insertStudents`(in stustr VARCHAR(5000))
BEGIN
declare str1 varchar(200);
declare num0 varchar(50);
DECLARE name0 varchar(50);
declare pw0 VARCHAR(50);
declare classid0 int;
while stustr >'' do
set str1=mid(stustr,1,locate(';',stustr)-1);
set num0=mid(str1,1,locate(',',str1)-1);
set str1=mid(str1,locate(',',str1)+1);
set name0=mid(str1,1,locate(',',str1)-1);
set str1=mid(str1,locate(',',str1)+1);
set pw0=mid(str1,1,locate(',',str1)-1);
set classid0=MID(str1,locate(',',str1)+1);
call insertStudent(num0,name0,pw0,classid0);

set stustr=mid(stustr,locate(';',stustr)+1);
end while;

END

2)使用临时变量

CREATE DEFINER=`root`@`localhost` PROCEDURE `xsjlcp`(in xsmx VARCHAR(50))
begin
drop table if exists lsb;
create TEMPORARY table lsb(hpid int,xssl decimal(18,3));
while(xsmx<>'') do
set @k=POSITION(',' in xsmx);
set @hpid=left(xsmx,@k-1);
set xsmx=substr(xsmx,@k+1);
set @k=position(',' in xsmx);
set @xssl=left(xsmx,@k-1);
insert into lsb values(@hpid,@xssl);
set xsmx=SUBSTR(xsmx,@k+1);
end while;
select * from lsb;

end

这篇关于mysql-学习01 数据库存储过程操作的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!