Mysql存儲過程之簡單使用

基礎查詢spa

首先建立一張students學生表,增長字段與插入數據以下code

建立不帶參數的存儲過程blog

查看學生個數ci

DROP PROCEDURE IF EXISTS select_students_count;  -- 沒有括號() 
DELIMITER ;;
CREATE PROCEDURE `select_students_count`()
BEGIN

    SELECT count(id) from students;

END;;
DELIMITER ;

執行存儲過程it

call select_students_count();

帶參數的存儲過程class

根據城市查詢總數基礎

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('杭州');

帶有輸出參數的存儲過程date

根據姓名查詢的學生信息,返回學生的城市select

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(對存儲過程傳入和傳出)類型的參數。存儲過程的代碼位於BEGINEND語句內,如前所見,它們是一系列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的那條記錄就刪除啦!

相關文章
相關標籤/搜索