Display records from MySQL stored Procedure with IF…THEN…END IF statements

MySQLMySQLi Database

Let us first create a table −

mysql> create table DemoTable643 (ClientId int);
Query OK, 0 rows affected (0.86 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable643 values(1000);
Query OK, 1 row affected (0.19 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable643;

This will produce the following output −

+----------+
| ClientId |
+----------+
| 1000    |
+----------+
1 row in set (0.00 sec)

Here is the query to MySQL stored procedure with IF THEN END IF −

mysql> DELIMITER //
mysql> CREATE PROCEDURE IF_DEMO(argument int)
   BEGIN
   DECLARE firstArgument int;
   DECLARE secondArgument int;
   set firstArgument=0;
   set secondArgument=1;
   IF firstArgument=argument THEN
      insert into DemoTable643 values(2000);
   END IF;
   IF secondArgument=argument THEN
   select *from DemoTable643;
      END IF;
   END
   //
Query OK, 0 rows affected (0.12 sec)
mysql> DELIMITER ;

Call the stored procedure using call command −

mysql> call IF_DEMO(0);
Query OK, 1 row affected (0.17 sec)

Here is the query to display all the records from the stored procedure −

mysql> call IF_DEMO(1);

This will produce the following output −

+----------+
| ClientId |
+----------+
| 1000     |
| 2000     |
+----------+
2 rows in set (0.00 sec)
Query OK, 0 rows affected (0.03 sec)
raja
Published on 23-Aug-2019 14:31:36
Advertisements