How to use an OUT parameter / read data with SELECT from table in a MySQL procedure?

MySQLMySQLi Database

For this, you can use SELECT INTO. Let us first create a table −

mysql> create table DemoTable1860
     (
     Amount int
     );
Query OK, 0 rows affected (0.00 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1860 values(1590);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1860 values(410);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1860 values(3000);
Query OK, 1 row affected (0.00 sec)

Display all records from the table using select statement −

Mysql> select * from DemoTable1860;

This will produce the following output −

+--------+
| Amount |
+--------+
|   1590 |
|    410 |
|   3000 |
+--------+
3 rows in set (0.00 sec)

Following is the query to create a stored procedure and use the OUT parameter −

mysql> delimiter //
mysql> create procedure use_of_out_parameter(out TotalAmount int)
     begin
     select sum(Amount) into TotalAmount from DemoTable1860;
     end
     //
Query OK, 0 rows affected (0.00 sec)
mysql> delimiter ;

Call a stored procedure using call command −

mysql> call use_of_out_parameter(@TotalAmount);
Query OK, 1 row affected (0.00 sec)

Now you can use the parameter variable −

mysql> select @TotalAmount;

This will produce the following output −

+--------------+
| @TotalAmount |
+--------------+
|         5000 |
+--------------+
1 row in set (0.00 sec)
raja
Published on 26-Dec-2019 11:16:30
Advertisements