Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

วิธีใช้ MySQL Stored Function ในคำสั่ง Query ฐานข้อมูล


ตัวอย่างสร้างฟังก์ชัน Profit คำนวณกำไร แล้วนำไปใช้ใน Query กับตาราง 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 //
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)

ใช้ฟังก์ชัน profit ใน Query:

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)

สรุป: เรียกใช้ Stored Function ใน SELECT list ได้เหมือนฟังก์ชัน Built-in โดยส่งคอลัมน์เป็นอาร์กิวเมนต์