mysql存储过程小例

来源:互联网 发布:canvas js库 编辑:程序博客网 时间:2024/06/14 21:17

表数据:

+----+------+--------+--------+| id | name | price1 | price2 |+----+------+--------+--------+|  1 | 大米 | 5      | 3      ||  2 | 鸡蛋 | 4.5    | 4.3    ||  3 | 苹果 | 6      | 4      ||  4 | 面粉 | 4      | 3      ||  5 | 小米 | 5.5    | 4      ||  6 | 大米 | 4      | 2      |+----+------+--------+--------+

创建存储过程:

delimiter //create procedure getPrice(in name varchar(50), in addable boolean, out ototal decimal(6,2))comment '一个简单注释'begin-- 声明临时变量totaldeclare total decimal(6,2);-- 根据name条件获取price1select price1 from aa01 where aa01.name = name into total;-- 判断是否需要加一遍IF addable THEN select total + total into total;END IF;-- 最后将临时变量赋值给输出变量select total into ototal;end //delimiter ;


调用存储过程:

call getPrice('小米', 1, @p);select @p;

mysql> call getPrice('小米', 1, @p);Query OK, 1 row affectedmysql> select @p;+-------+| @p    |+-------+| 11.00 |+-------+1 row in set

注:BOOLEAN值指定为1表示真,指定为0表示假(实际上,非零值都考虑为真,只有0被视为假)。