สามารถดำเนินการคำนวณทางคณิตศาสตร์พื้นฐาน (+, -, *, /, %) ได้ภายใน MySQL Stored Procedure โดยตรงในคำสั่ง SELECT หรือกำหนดให้ตัวแปร
ตัวอย่าง: คำนวณราคารวม = ราคาต่อหน่วย × จำนวน
1. สร้าง Stored Procedure รับพารามิเตอร์ 2 ตัว
mysql> delimiter //
mysql> create procedure calculation_proc(amount int, quantity int)
-> begin
-> select amount, quantity, (amount * quantity) as Total;
-> end
-> //
Query OK, 0 rows affected (0.00 sec)
mysql> delimiter ;
2. เรียกใช้งาน
mysql> call calculation_proc(250, 3);
ผลลัพธ์:
+--------+----------+-------+ | amount | quantity | Total | +--------+----------+-------+ | 250 | 3 | 750 | +--------+----------+-------+ 1 row in set (0.00 sec)
ตัวดำเนินการคณิตศาสตร์ใน MySQL
| ตัวดำเนินการ | ความหมาย | ตัวอย่าง | ผลลัพธ์ |
|---|---|---|---|
| + | บวก | 10 + 5 | 15 |
| - | ลบ | 10 - 5 | 5 |
| * | คูณ | 10 * 5 | 50 |
| / | หาร (ทศนิยม) | 10 / 4 | 2.5 |
| DIV | หารจำนวนเต็ม | 10 DIV 4 | 2 |
| % หรือ MOD | หารเอาเศษ | 10 % 4 | 2 |
ตัวอย่างขั้นสูง: ใช้ตัวแปร DECLARE
mysql> delimiter //
mysql> create procedure calc_discount(price decimal(10,2), discount_percent int)
-> begin
-> declare discount_amount decimal(10,2);
-> declare final_price decimal(10,2);
-> set discount_amount = price * discount_percent / 100;
-> set final_price = price - discount_amount;
-> select price as OriginalPrice, discount_amount as Discount, final_price as FinalPrice;
-> end
-> //
Query OK, 0 rows affected (0.00 sec)
mysql> delimiter ;
mysql> call calc_discount(1000.00, 20);
+---------------+----------+------------+
| OriginalPrice | Discount | FinalPrice |
+---------------+----------+------------+
| 1000.00 | 200.00 | 800.00 |
+---------------+----------+------------+
สรุป: MySQL Stored Procedure รองรับตัวดำเนินการคณิตศาสตร์มาตรฐานทั้งหมด สามารถคำนวณได้ทั้งใน SELECT โดยตรง หรือผ่านตัวแปร DECLARE/SET สำหรับตรรกะที่ซับซ้อนขึ้น