mysql存储过程语法学习
一个存储过程包括名字,参数列表,以及可以包括很多SQL语句的SQL语句集。
创建存储过程:
语法: CREATE PROCEDURE p() BEGIN /*此存储过程的正文*/ END |
CREATE PROCEDURE productpricing() BEGIN SELECT Avg(pro_price) AS priceaverage FROM products; END; # begin…end之间是存储过程的主体定义 # mysql的分界符是分号(;) |
调用存储过程的方法是:
# CALL加上过程名以及一个括号 # 例如调用上面定义的存储过程 CALL productpricing(); # 哪怕是不用传递参数,存储过程名字后面的括号“()”也是必须的 |
删除存储过程的方法是:
DROP PROCUDURE productpricing; |
创建带参数的存储过程:
CREATE PROCUDURE productpricing( OUT p1 DECIMAL(8,2), OUT ph DECIMAL(8,2), OUT pa DECIMAL(8,2) ) BEGIN SELECT Min(prod_price) INTO pl FROM products; SELECT Max(prod_price) INTO ph FROM products; SELECT Avg(prod_price) INTO pa FROM products; END; # DECIMAL用于指定参数的数据类型 # OUT用于表明此值是用于从存储过程里输出的 # MySQL支持 OUT, IN, INOUT |
调用带参数的存储过程:
CALL productpricing(@pricelow, @pricehigh, @priceaverage); # 所有的参数必须以@开头 # 要想获取@priceaverage的值,用以下语句 SELECT @priceaverage; # 获取三个的值,用以下语句 SELECT @pricehigh, @pricelow, @priceaverage; |
另一个带IN和OUT参数的存储过程:
CREATE PROCEDURE ordertotal( IN onumber INT, OUT ototal DECIMAL(8,2) ) BEGIN SELECT Sum(item_price*quantity) FROM orderitems WHERE order_num = onumber INTO ototal; END; CALL ordertotal(20005, @total); SELECT @total; |
DELIMITER $$
DROP PROCEDURE IF EXISTS `dbcall`.`get_page`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `get_page`(
/**//*Table name*/
tableName varchar(100),
/**//*Fileds to display*/
fieldsNames varchar(100),
/**//*Page index*/
pageIndex int,
/**//*Page Size*/
pageSize int,
/**//*Field to sort*/
sortName varchar(500),
/**//*Condition*/
strWhere varchar(500)
)
BEGIN
DECLARE fieldlist varchar(200);
if fieldsNames=''||fieldsNames=null THEN
set fieldlist='*';
else
set fieldlist=fieldsNames;
end if;
if strWhere=''||strWhere=null then
if sortName=''||sortName=null then
set @strSQL=concat('SELECT ',fieldlist,' FROM ',tableName,' LIMIT ',(pageIndex-1)*pageSize,',',pageSize);
else
set @strSQL=concat('SELECT ',fieldlist,' FROM ',tableName,' ORDER BY ',sortName,' LIMIT ',(pageIndex-1)*pageSize,',',pageSize);
end if;
else
if sortName=''||sortName=null then
set @strSQL=concat('SELECT ',fieldlist,' FROM ',tableName,' WHERE ',strWhere,' LIMIT ',(pageIndex-1)*pageSize,',',pageSize);
else
set @strSQL=concat('SELECT ',fieldlist,' FROM ',tableName,' WHERE ',strWhere,' ORDER BY ',sortName,' LIMIT ',(pageIndex-1)*pageSize,',',pageSize);
end if;
end if;
PREPARE stmt1 FROM @strSQL;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;
END$$
DELIMITER ;