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

คำนวณคณิตศาสตร์ใน MySQL Stored Procedure

สามารถดำเนินการคำนวณทางคณิตศาสตร์พื้นฐาน (+, -, *, /, %) ได้ภายใน 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 + 515
-ลบ10 - 55
*คูณ10 * 550
/หาร (ทศนิยม)10 / 42.5
DIVหารจำนวนเต็ม10 DIV 42
% หรือ MODหารเอาเศษ10 % 42

ตัวอย่างขั้นสูง: ใช้ตัวแปร 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 สำหรับตรรกะที่ซับซ้อนขึ้น