MySQL stored procedure to return a column value?

MySQLMySQLi Database

Let us first create a table −

mysql> create table DemoTable
   -> (
   -> Id int,
   -> Score int
   -> );
Query OK, 0 rows affected (0.69 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(1,858858686);
Query OK, 1 row affected (0.11 sec)

mysql> insert into DemoTable values(2,9900554);
Query OK, 1 row affected (0.22 sec)

mysql> insert into DemoTable values(3,646565667);
Query OK, 1 row affected (0.15 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

This will produce the following output −

+------+-----------+
| Id   | Score     | 
+------+-----------+
| 1    | 858858686 |
| 2    | 9900554   |
| 3    | 646565667 |
+------+-----------+
3 rows in set (0.00 sec)

Following is the MySQL stored procedure −

mysql> DELIMITER //
mysql> CREATE PROCEDURE Test_StoredProcedure(in id INT, OUT scoreValue INT)
-> BEGIN
-> SELECT Score
-> INTO scoreValue
-> FROM DemoTable tbl
-> WHERE tbl.Id = id;
-> END
-> //
Query OK, 0 rows affected (0.18 sec)
mysql> DELIMITER ;

Now, call the stored procedure with the help of call command and store the output into a variable name called ‘@result’ −

mysql> call Test_StoredProcedure(2,@result);
Query OK, 1 row affected (0.00 sec)

Now display the variable value using select statement −

mysql> select @result;

Output

This will produce the following output −

+---------+
| @result |
+---------+
| 9900554 |
+---------+
1 row in set (0.00 sec)
raja
Published on 12-Jul-2019 16:15:04
Advertisements