Create a procedure in MySQL with parameters?

MySQLMySQLi Database

You can create a parameter using IN and OUT. IN is used to take input parameter and OUT can be used for output.

The syntax is as follows

DELIMITER //
CREATE PROCEDURE yourProcedureName(IN yourParameterName dataType,OUT
   yourParameterName dataType
)
BEGIN
yourStatement1;
yourStatement2;
.
.
N
END;
//
DELIMITER ;

First, we will create a table. The query to create a table is as follows

mysql> create table SumOfAll
   -> (
   -> Amount int
   -> );
Query OK, 0 rows affected (0.78 sec)

Insert some records in the table using insert command. The query is as follows

mysql> insert into SumOfAll values(100);
Query OK, 1 row affected (0.18 sec)

mysql> insert into SumOfAll values(330);
Query OK, 1 row affected (0.24 sec)

mysql> insert into SumOfAll values(450);
Query OK, 1 row affected (0.10 sec)

mysql> insert into SumOfAll values(400);
Query OK, 1 row affected (0.20 sec)

Display all records from the table using select statement. The query is as follows

mysql> select *from SumOfAll;

The following is the output

+--------+
| Amount |
+--------+
| 100    |
| 330    |
| 450    |
| 400    |
+--------+
4 rows in set (0.00 sec)

Now, we will create a stored procedure that will check the value is present in the table or not. If the given value is not present in the table then you will get a NULL value.

The stored procedure is as follows

mysql> DELIMITER //
mysql> create procedure sp_ChechValue(IN value1 int,OUT value2 int)
   -> begin
   -> set value2=(select Amount from SumOfAll where Amount=value1);
   -> end;
   -> //
Query OK, 0 rows affected (0.20 sec)
mysql> delimiter ;

Let us call the stored procedure with some value and store the output in a session variable.

Case 1: When the value is not present in the table.

mysql> call sp_ChechValue(300,@isPresent);
Query OK, 0 rows affected (0.00 sec)

Now check the value in a variable @isPresent using the select statement. The query is as follows

mysql> select @isPresent;

The following is the output

+------------+
| @isPresent |
+------------+
| NULL       |
+------------+
1 row in set (0.00 sec)

Case 2: When the value is present.

The query is as follows. Let us call the stored procedure

mysql> call sp_ChechValue(330,@isPresent);
Query OK, 0 rows affected (0.00 sec)

Check the value of a session variable @isPresent. The query is as follows

mysql> select @isPresent;

The following is the output

+------------+
| @isPresent |
+------------+
| 330        |
+------------+
1 row in set (0.00 sec)
raja
Published on 16-Jan-2019 13:05:18
Advertisements