create procedure GetUsers() begin select * from user; end;
调用存储过程:
call GetUsers();
删除存储过程:
drop procedure if exists GetUsers;
4. 带参数的存储过程
MySql 支持 IN (传递给存储过程) , OUT (从存储过程传出) 和 INOUT (对存储过程传入和传出) 类型的参数 , 存储过程的代码位于 BEGIN 和 END 语句内 , 它们是一系列 SQL 语句 , 用来检索值 , 然后保存到相应的变量 (通过指定INTO关键字) ;
下面的存储过程接受三个参数 , 分别用于获取用户表的最小 , 平均 , 最大分数 , 每个参数必须具有指定的类型 , 这里使用十进制值(decimal(8,2)) , 关键字 OUT 指出相应的参数用来从存储过程传出:
create procedure GetScores( out minScore decimal(8,2), out avgScore decimal(8,2), out maxScore decimal(8,2) ) begin select min(score) into minScore from user; select avg(score) into avgScore from user; select max(score) into maxScore from user; end;
call GetScores(@minScore, @avgScore, @maxScore);
该调用并没有任何输出 , 只是把调用的结果赋给了调用时传入的变量 @minScore, @avgScore, @maxScore , 然后即可调用显示该变量的值 :
create procedure GetNameByID( in userID int, out userName varchar(200) ) begin select name from user where id = userID into userName; end; 123456789 调用存储过程 : call GetNameByID(1, @userName); select @userName; 12
create procedure GetPriceByID( in prodID int, in isDisc boolean, out prodPrice decimal(8,2) ) begin declare tmpPrice decimal(8,2); declare prodDiscRate decimal(8,2); set prodDiscRate = 0.88; select price from products where id = prodID into tmpPrice; if isDisc then select tmpPrice*prodDiscRate into tmpPrice; end if; select tmpPrice into prodPrice; end; 1234567891011121314151617181920 该存储过程传入三个参数 , 货品 ID , 是否折扣以及返回的价格 , 在存储过程内部 , 定义两个局部变量 tmpPrice 和 prodDiscRate , 把查询出来的结果赋给临时变量 , 再判断是否折扣 , 最后把局部变量的值赋给输出参数 ; 调用如下 : call GetPriceByID(1, true, @prodPrice); select @prodPrice; 12
6. DELIMITER
DELIMITER $$ create procedure getUsers() begin select * from user; end $$ DELIMITER ; DELIMITER $$ CREATE PROCEDURE getcount() BEGIN SELECT * FROM contract_user; END $$ DELIMITER ; CALL getcount();
原文:https://www.cnblogs.com/hkMblogs/p/13186311.html