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

การใช้เงื่อนไข IF ใน MySQL Stored Procedure ให้ถูกต้อง

ไวยากรณ์การใช้ IF ใน Stored Procedure

if yourCondition then 
    yourStatement1; 
else 
    yourStatement2; 
end if; 
end //

ตัวอย่าง Stored Procedure ที่ถูกต้อง

mysql> delimiter // 
mysql> create procedure Test_Demo(In inputValue int) 
    -> BEGIN 
    -> if inputValue=10 then 
    -> select 'You have won 100$'; 
    -> else 
    -> select 'Sorry !!!'; 
    -> end if; 
    -> end 
    -> // 
Query OK, 0 rows affected (0.20 sec) 
mysql> delimiter ;

การเรียกใช้ Stored Procedure

mysql> call Test_Demo(10);

ผลลัพธ์

+-------------------+ 
| You have won 100$ | 
+-------------------+ 
| You have won 100$ | 
+-------------------+ 
1 row in set (0.00 sec)

จุดสำคัญ: ใช้ delimiter // ก่อนสร้าง procedure และ delimiter ; หลังจบ เพื่อไม่ให้เครื่องหมาย ; ภายใน procedure ทำให้คำสั่งจบก่อนเวลา