One, what is a stored procedure
Simply put, it is a set of SQL statements with powerful functions that can implement some more complex logic functions, which is a bit similar to a functional function of an application.
Stored procedures are similar to triggers. They are both a set of SQL sets, but stored procedures are actively invoked and have more powerful functions than triggers. Triggers are automatically invoked after something is triggered;
Second, the characteristics of the stored procedure
There are input and output parameters, variables can be declared, there are control statements such as if/else, case, while, etc., and complex logic functions can be realized by writing stored procedures;
General features of functions: modularization, encapsulation, code reuse;
Fast speed, only the first execution needs to go through the compilation and optimization steps, and the subsequent calls can be executed directly, eliminating the above steps;
Based on the above characteristics, some modules with high performance requirements and complex services can be written into the stored procedure and called directly by the application layer.
Three, create a simple stored procedure
3.1 Basic grammar
CREATE PROCEDURE pro_now() -- 存储过程名称,自定义
BEGIN -- 开始存储过程
# 需要执行操作的sql语句集,可对数据表 进行CRUD 操作
-- insert some sql here
end; -- 结束存储过程
3.2. Create a stored procedure to query the current time:
CREATE PROCEDURE pro_now()
BEGIN
SELECT now();
END;
3.3. Call a stored procedure: call pro_now(); – call keyword, "pro_now()" stored procedure name
3.4. View the created stored procedure: show PROCEDURE STATUS [where name='pro_now'];
3.5, delete the stored procedure: DROP PROCEDURE pro_now;-"pro_now" stored procedure name
Fourth, create a stored procedure with parameters
4.1. For stored procedures with input parameters, use keywords: in
a. Examples are as follows:
CREATE PROCEDURE pro_now_in(in time VARCHAR(20) CHARACTER set "utf8")
-- CHARACTER set "utf8",设定字符集,解决中文乱码
BEGIN
SELECT now(),time;
end;
b, call the stored procedure:
set @time='当前时间';
call pro_now_in(@time); -- call pro_now_in('当前时间'); 这样也可以
c. The results are as follows:
4.2 Stored procedures with output parameters, use keywords: out
a. Examples are as follows:
CREATE PROCEDURE pro_now_out(out time VARCHAR(20),out title VARCHAR(20) CHARACTER set utf8)
BEGIN
SELECT now(),'当前时间' into time , title;
end;
b, call the stored procedure:
call pro_now_out(@times,@title);
SELECT @title AS "标题",@times AS "时间";
c. Results:
4.3. For stored procedures with input and output parameters, use keywords: inout
a. Examples are as follows:
CREATE PROCEDURE pro_now_inout(inout name VARCHAR(20),in title VARCHAR(10), out time VARCHAR(10))
BEGIN
SELECT CONCAT(name,'<--->',title) AS name,now() into name,time;
end;
b, call the stored procedure:
set @name='jack';
set @title='toady';
call pro_now_inout(@name,@title,@time);
select @name as 'name and title',@time as 'time';
c. Results:
d. Understanding:
in (input): name, title
out (output): name, time
CONCAT(name,'<—>',title) String concatenation, corresponding to name output, now() corresponding to time output.
Five, create a stored procedure with control flow
5.1. If statement
a, an example is as follows:
CREATE PROCEDURE pro_if(in num INT)
BEGIN
DECLARE result VARCHAR(20) CHARACTER set utf8 DEFAULT null;
IF num = 0 THEN -- 开始if判断,注意用一个等号"="
set result='num 为0啦'; -- 满足条件
ELSEIF num > 0 THEN -- 下一个if判断
set result='num 大于 0';
ELSEIF num < 0 THEN
set result='num 小于 0';
ELSE -- 所有条件不满足的情况下
set result='num is null or other status';
end if; -- 结束if 判断
SELECT result;
end;
b, call the stored procedure:
call pro_if('33');
c. The results are as follows:
、
5.2 case statement
a. Examples are as follows:
CREATE PROCEDURE pro_case(in num INT)
BEGIN
DECLARE result VARCHAR(20) CHARACTER set utf8 DEFAULT null;
case num -- 开始case 判断
when 2 THEN -- 满足条件执行
set result='num 值是2';
when -2 THEN
set result='num 值是-2';
else -- 所有条件不满足,执行
set result='num 不等于2和-2';
end case ; -- 结束case语句
SELECT result;
end;
b, call the stored procedure:
call pro_case(-2);
c. The results are as follows:
5.3, while loop statement
a. Examples are as follows:
CREATE PROCEDURE pro_while(in num INT)
BEGIN
DECLARE i int;
DECLARE result int;
set i=0;
set result=0;
while i < num DO -- 开始while 循环
set result=result+i;
set i=i+1;
end while; -- 结束while 循环
SELECT result,i;
end;
b, call the stored procedure:
call pro_while(100);
c. The results are as follows:
Six, create a stored procedure with a cursor loop
1. Examples are as follows:
CREATE PROCEDURE pro_cursor(out count int)
BEGIN
declare paper_id VARCHAR(1000) ; -- 论文主键id
declare doctroName VARCHAR(1000) character set gbk; -- 医生名称
DECLARE paper_hos VARCHAR(1000); -- 医院id
DECLARE paper_room VARCHAR(100); -- 医生专业
declare done int DEFAULT false ; -- 自定义控制游标循环变量,默认false
DECLARE my_cursor CURSOR for (SELECT id,authorName,hospitalId,room
from yee_article_paper_authorid ); -- 定义游标并输入结果集
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done=TRUE; -- 绑定控制变量到游标,游标循环结束自动转true
OPEN my_cursor; -- 打开游标
myLoop:LOOP -- 开始循环体,myLoop为自定义循环名,结束循环时用到
FETCH my_cursor into paper_id,doctroName,paper_hos,paper_room ; -- 将游标当前读取行的数据顺序赋予自定义变量12
if done THEN -- 判断是否继续循环
LEAVE myLoop;-- 结束循环
END IF;
-- 自己要做的事情,在 sql 中直接使用自定义变量即可
insert into temp(str_id,name,hospitalId,room)
VALUES(paper_id,doctroName,paper_hos,paper_room);
COMMIT; -- 提交事务
END LOOP myLoop; -- 结束 自定义循环体
CLOSE my_cursor; -- 关闭游标
# 循环结束后,统计导入个数
SELECT count(id) count from temp into count; -- 计算个数
end
Cursor is a method of processing data. In order to view or process the data in the result set, the cursor provides the ability to browse the data one or more rows at a time in the result set.
Seven, Spring mvc calls stored procedures
The SimpleJdbcCall class can be used to call a stored procedure containing IN and OUT parameters . You can use this method when dealing with any RDBMS, such as Apache Derby, DB2, MySQL, Microsoft SQL Server, Oracle, and Sybase.
7.1 Create a table:
CREATE TABLE ssers(
ID INT NOT NULL AUTO_INCREMENT,
NAME VARCHAR(20) NOT NULL,
AGE INT NOT NULL,
PRIMARY KEY (ID)
);
7.2 Create a stored procedure:
DELIMITER $$
DROP PROCEDURE IF EXISTS `TEST`.`getRecord` $$
CREATE PROCEDURE `TEST`.`getRecord` (
IN in_id INTEGER,
OUT out_name VARCHAR(20) CHARACTER set "utf8",
OUT out_age INTEGER
)
BEGIN
SELECT name, age
INTO out_name,out_age
FROM users where id = in_id;
END $$
DELIMITER ;
delimiter is a command in MySQL, this command has nothing to do with stored procedures.
In fact, it tells the mysql interpreter whether the command has ended and whether mysql can be executed.
That is to change the input terminator.
By default, the delimiter is a semicolon ";".
7.3 dao layer call stored procedure
Public class UserDaoImpl implements UserDao {
@Autowired
private JdbcTemplate myJdbc;
@Autowired
private DataSource dataSource;
private UserModel userModel;
@Override
public UserModel getUser(int id){
//创建jdbccall对象
SimpleJdbcCall jdbcCall = new SimpleJdbcCall(dataSource).withProcedureName("getRecord");
//调用存储过程
SqlParameterSource in = new MapSqlParameterSource().addValue("in_id", id);
Map<String, Object> out = jdbcCall.execute(in);
UserModel user = new UserModel(0,null,0);
user.setId(id);
user.setName((String) out.get("out_name"));
user.setAge((Integer) out.get("out_age"));
return user;
//普通的sql查询
//String SQL = "select * from users id = ?";
//UserModel user = myJdbc.queryForObject(SQL,new Object[]{id}, new UserMapper());
//return user;
}
}
8. Disadvantages of stored procedures
Different databases have very different grammars and are difficult to transplant. If the database is changed, it needs to be rewritten;
It is not easy to manage. It is not easy to maintain too much business logic in the storage process, which is not conducive to hierarchical management, and is easy to be confused. The general storage process is suitable for individual businesses with high performance requirements, and other necessity is not great;
Reference link:
https://blog.csdn.net/HaHa_Sir/article/details/79728854
https://www.cnblogs.com/chenpi/p/5136483.html
https://www.w3cschool.cn/wkspring/3yh61mmc.html