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

การใช้ WHERE IN() ใน MySQL Stored Procedure

สร้าง Stored Procedure ที่รับค่า IN clause แบบไดนามิก

สร้างตารางและข้อมูล

mysql> create table DemoTable ( Id int, Name varchar(20) ); 
Query OK, 0 rows affected (0.69 sec)
mysql> insert into DemoTable values(100,'Chris'); 
Query OK, 1 row affected (0.12 sec) 
mysql> insert into DemoTable values(101,'Bob'); 
Query OK, 1 row affected (0.18 sec) 
mysql> insert into DemoTable values(102,'David'); 
Query OK, 1 row affected (0.18 sec)

Stored Procedure ใช้ Prepared Statement

mysql> DELIMITER // 
mysql> CREATE PROCEDURE whereInDemo(in input varchar(100)) 
    -> BEGIN 
    -> set @Query = 'select Name from DemoTable '; 
    -> set @Query = CONCAT(@Query,' where Id IN (',`input`,')'); 
    -> prepare stmt from @Query; 
    -> execute stmt; 
    -> deallocate prepare stmt; 
    -> END // 
Query OK, 0 rows affected (0.23 sec) 
mysql> DELIMITER ;

เรียกใช้ Procedure

mysql> call whereInDemo('100,102');

ผลลัพธ์

+-------+ 
| Name  | 
+-------+ 
| Chris | 
| David | 
+-------+ 
2 rows in set (0.04 sec)

เทคนิค: ใช้ CONCAT สร้างคิวรี่ไดนามิก แล้ว PREPARE / EXECUTE / DEALLOCATE PREPARE เพื่อรันคิวรี่ที่สร้างขึ้น