基础查询
首先创建一张students学生表,增加字段与插入数据如下
创建不带参数的存储过程
查看学生个数
DROP PROCEDURE IF EXISTS select_students_count; -- 没有括号()
DELIMITER ;; CREATE PROCEDURE `select_students_count`() BEGIN SELECT count(id) from students; END;; DELIMITER ;
执行存储过程
call select_students_count();
带参数的存储过程
根据城市查询总数
DROP PROCEDURE IF EXISTS select_students_by_city_count;
DELIMITER ;; CREATE PROCEDURE `select_students_by_city_count`( in _city varchar(225) ) BEGIN SELECT count(id) from students where city = _city; END;; DELIMITER ;
执行存储过程
call select_students_by_city_count('杭州');
带有输出参数的存储过程
根据姓名查询的学生信息,返回学生的城市
DROP PROCEDURE IF EXISTS select_students_by_name;
DELIMITER ;; CREATE PROCEDURE `select_students_by_name`( in _name varchar(225), -- 输入参数 out _city varchar(225), -- 输出参数 inout _age int(11) -- 输入输出参数 ) BEGIN SELECT city from students where name = _name and age = _age into _city; END;; DELIMITER ;
执行存储过程
set @_age = 20; set @_name = 'jack'; call select_students_by_name(@_name, @_city, @_age); select @_city as city, @_age as age;
MySQL支持IN(传递给存储过程),OUT(从存储过程传出)和INOUT(对存储过程传入和传出)类型的参数。存储过程的代码位于BEGIN和END语句内,如前所见,它们是一系列SELECT语句,用来检索值,然后保存到相应的变量(通过指定INTO关键字)
带有通配符的存储过程
通配符,在参数值赋值时,加上相应的通配符
DROP PROCEDURE IF EXISTS select_students_by_likename;
DELIMITER ;; CREATE PROCEDURE `select_students_by_likename`( in _likename varchar(225) ) BEGIN set _likename = '%s%'; -- 默认值 SELECT * from students where name like _likename; END;; DELIMITER ;
执行存储过程
call select_students_by_likename('%s%');
使用存储过程进行增删改
新增
新增学生信息
DROP PROCEDURE IF EXISTS insert_student;
DELIMITER ;; CREATE PROCEDURE `insert_student`( _id int, _name varchar(225), _age int, _city varchar(225) ) BEGIN INSERT INTO students(ID,name,age,city) VALUES(_id,_name,_age,_city); END;; DELIMITER ;
执行存储过程
call insert_student(5,'张三',19,'上海');
执行完后表中就多了一条数据
修改
根据学生ID,更新学生信息
DROP PROCEDURE IF EXISTS update_student;
DELIMITER ;; CREATE PROCEDURE `update_student`( _id int, _name varchar(225), _age int, _city varchar(225) ) BEGIN UPDATE students SET name=_name, age=_age, city=_city where ID = _id; END;; DELIMITER ;
执行存储过程
call update_student(5,'amy',22,'杭州');
删除
根据ID,删除某学生记录
DROP PROCEDURE IF EXISTS delete_student_by_id;
DELIMITER ;; CREATE PROCEDURE `delete_student_by_id`( _id int ) BEGIN DELETE FROM students where ID = _id; END;; DELIMITER ;
执行存储过程
call delete_student_by_id(5);
students表中id为5的那条记录就删除了