ตัวอย่างฟังก์ชันเก็บสำหรับคำนวณแฟกทอเรียล
นี่คือตัวอย่างของฟังก์ชันเก็บ (Stored Function) ที่สามารถคำนวณแฟกทอเรียลของตัวเลขที่กำหนดได้:
CREATE FUNCTION factorial (n DECIMAL(3,0)) RETURNS DECIMAL(20,0) DETERMINISTIC
BEGIN
DECLARE factorial DECIMAL(20,0) DEFAULT 1;
DECLARE counter DECIMAL(3,0);
SET counter = n;
factorial_loop: REPEAT
SET factorial = factorial * counter;
SET counter = counter - 1;
UNTIL counter = 1 END REPEAT;
RETURN factorial;
END //
การทดสอบฟังก์ชัน
mysql> Select Factorial(5)// +--------------+ | Factorial(5) | +--------------+ | 120 | +--------------+ 1 row in set (0.27 sec) mysql> Select Factorial(6)// +--------------+ | Factorial(6) | +--------------+ | 720 | +--------------+ 1 row in set (0.00 sec)
คำอธิบาย: ฟังก์ชันนี้รับพารามิเตอร์ n เป็น DECIMAL(3,0) และคืนค่าเป็น DECIMAL(20,0) ใช้ลูป REPEAT...UNTIL เพื่อคูณค่าตัวเลขตั้งแต่ n ลงมาจนถึง 1