สร้างตารางและข้อมูลตัวอย่าง
mysql> create table DemoTable1971 ( StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, StudentName varchar(20), StudentPassword int );
mysql> insert into DemoTable1971(StudentName,StudentPassword) values('John','123456');
mysql> insert into DemoTable1971(StudentName,StudentPassword) values('Chris','123456');
mysql> insert into DemoTable1971(StudentName,StudentPassword) values('David','123456');
mysql> insert into DemoTable1971(StudentName,StudentPassword) values('Mike','123456');
สร้าง Stored Procedure
รับพารามิเตอร์ pass มาเปรียบเทียบกับ StudentPassword:
mysql> delimiter //
mysql> create procedure returnAll(pass varchar(30))
begin
select * from DemoTable1971 where StudentPassword=pass;
end //
mysql> delimiter ;
เรียกใช้ Procedure
mysql> call returnAll('123456');
ผลลัพธ์
+-----------+-------------+-----------------+ | StudentId | StudentName | StudentPassword | +-----------+-------------+-----------------+ | 1 | John | 123456 | | 2 | Chris | 123456 | | 3 | David | 123456 | | 4 | Mike | 123456 | +-----------+-------------+-----------------+ 4 rows in set (0.00 sec)
ข้อสังเกต
- Procedure นี้คืนค่า Result Set โดยตรง (ไม่ใช่ OUT parameter)
- ใน Production ควรหลีกเลี่ยงเก็บรหัสผ่านเป็น Plain Text ควรใช้ Hashing (bcrypt, Argon2)
- ประเภทข้อมูล
VARCHAR(30)สำหรับพารามิเตอร์ pass ควรตรงกับคอลัมน์StudentPassword(ที่นี่เป็น INT แต่ส่งเป็น String ก็ได้เพราะ MySQL แปลงอัตโนมัติ)
รูปแบบที่ดีกว่าสำหรับการยืนยันตัวตน
CREATE PROCEDURE verify_login(IN p_username VARCHAR(50), IN p_password_hash VARCHAR(255))
BEGIN
SELECT StudentId, StudentName FROM DemoTable1971
WHERE StudentName = p_username AND StudentPassword = p_password_hash;
END;