MYSQL Stored procedure to fetch entire row from a table
-
06-03-2021 - |
题
I am a beginner to SQL and currently practicing the concept of the stored procedure. I have a table Fetch_Marks that contains 20 records with Student_No and Marks as columns. Now I would like to create a stored procedure for this in which the input parameter will be Student_No and when we enter the input (Let's say I gave the Student_No as 1), it should fetch the row of that particular student from the table Fetch_Marks. Is there any workaround for this? If yes, please help.
解决方案
You basically don't need a procedure for that.
Procedures get interesting with CURSOR and LOOP when you need "normal" programming besides SQL to makes some thong much more complex
DROP procedure IF EXISTS `proc_get Student`;
DELIMITER $$
CREATE PROCEDURE `proc_get Student` ( IN _student_no BIGINT)
BEGIN
SELECT * FROM Fetch_Marks WHERE Student_No = _student_no;
END$$
DELIMITER ;
But I am guessing this is some kind of homework, the variable _student_no is as it is because you have so a optical marker that it is a locally defined variable
Here's another example: In this, we are adding a second IN variable and in which both are checked if they are NULL or NOT and then selects the wanted data
DROP procedure IF EXISTS `proc_get Student`;
DELIMITER $$
CREATE DEFINER=`root`@`%` PROCEDURE `proc_get Student`( IN _student_no BIGINT,IN _roll_no BIGINT)
BEGIN
IF ( _student_no IS NOT NULL AND _roll_no IS NULL) THEN
SELECT * FROM Fetch_Marks WHERE Student_No = _student_no;
END IF;
END$$
DELIMITER ;