我们如何在数据库查询中使用MySQL存储函数?
通过以下示例可以理解它,在该示例中,我们创建了一个函数“Profit”来计算利润,并通过在数据库查询中使用该函数将其应用于表“item_list”的数据。
示例
mysql> CREATE FUNCTION profit(Cost DECIMAL (10,2),Price DECIMAL(10,2))
-> RETURNS DECIMAL(10,2)
-> BEGIN
-> DECLARE profit DECIMAL(10,2);
-> SET profit = price - cost;
-> RETURN profit;
-> END //
mysql> Select * from item_list;
+-----------+-------+-------+
| Item_name | Price | Cost |
+-----------+-------+-------+
| Notebook | 24.50 | 20.50 |
| Pencilbox | 78.50 | 75.70 |
| Pen | 26.80 | 19.70 |
+-----------+-------+-------+
3 rows in set (0.00 sec)上面的查询显示了表item_list中的数据。现在,在数据库查询中使用上面创建的函数“profit”,如下所示:
mysql> Select *, profit(cost, price) AS Profit from item_list; +-----------+-------+-------+--------+ | Item_name | Price | Cost | Profit | +-----------+-------+-------+--------+ | Notebook | 24.50 | 20.50 | 4.00 | | Pencilbox | 78.50 | 75.70 | 2.80 | | Pen | 26.80 | 19.70 | 7.10 | +-----------+-------+-------+--------+ 3 rows in set (0.00 sec)