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

วิธีสร้าง Stored Procedure เพื่อลบข้อมูลจากตาราง MySQL

เราสามารถสร้าง stored procedure พร้อมตัวดำเนินการ IN เพื่อลบค่าจากตาราง MySQL เพื่อให้เข้าใจ เราใช้ตัวอย่างตารางชื่อ 'student_info' ที่มีข้อมูลดังนี้

mysql> Select * from student_info;
+------+---------+------------+------------+
| id   | Name    | Address    | Subject    |
+------+---------+------------+------------+
| 100  | Aarav   | Delhi      | Computers  |
| 101  | YashPal | Amritsar   | History    |
| 105  | Gaurav  | Jaipur     | Literature |
| 110  | Rahul   | Chandigarh | History    |
+------+---------+------------+------------+
4 rows in set (0.00 sec)

ตอนนี้ โดยการสร้าง procedure ชื่อ 'delete_studentinfo' ตามนี้ เราสามารถลบค่าจากตาราง 'student_info' ได้

mysql> DELIMITER // ;
mysql> Create Procedure Delete_studentinfo ( IN p_id INT)
    -> BEGIN
    -> DELETE FROM student_info
    -> WHERE ID=p_id;
    -> END //
Query OK, 0 rows affected (0.11 sec)
mysql> DELIMITER ; //

ตอนนี้ เรียกใช้ procedure ด้วยค่าที่เราต้องการลบจากตาราง ดังนี้

mysql> CALL Delete_studentinfo(100);
Query OK, 1 row affected (1.09 sec)
mysql> Select * from student_info;
+------+---------+------------+------------+
| id   | Name    | Address    | Subject    |
+------+---------+------------+------------+
| 101  | YashPal | Amritsar   | History    |
| 105  | Gaurav  | Jaipur     | Literature |
| 110  | Rahul   | Chandigarh | History    |
| 125  | Raman   | Bangalore  | Computers  |
+------+---------+------------+------------+
4 rows in set (0.01 sec)

ชุดผลลัพธ์ข้างต้นแสดงว่าระเบียนที่มี id = 100 ถูกลบจากตารางแล้ว