Ví dụ minh họa: tạo hàm Profit tính lợi nhuận và áp dụng vào truy vấn trên bảng item_list.
Ví dụ
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 //
Query OK, 0 rows affected (0.07 sec)
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)
Sử dụng hàm profit trong truy vấn:
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)
Giải thích:
- Hàm nhận 2 tham số
CostvàPrice, trả vềPrice - Cost - Trong truy vấn, gọi hàm như một hàm tích hợp:
profit(cost, price) - Cột kết quả được đặt alias
AS Profit - Hàm lưu trữ giúp đóng gói logic tính toán, tái sử dụng dễ dàng