Working with WHERE IN() in a MySQL Stored Procedure


Let us first create a table −

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

Insert some records in the table using insert command −

mysql> insert into DemoTable values(100,'Chris');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values(101,'Bob');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values(102,'David');
Query OK, 1 row affected (0.18 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable;

This will produce the following output −

+------+-------+
| Id   | Name  |
+------+-------+
|  100 | Chris |
|  101 | Bob   |
|  102 | David |
+------+-------+
3 rows in set (0.00 sec)

Here is the query to create a stored procedure to use WHERE IN() −

mysql> DELIMITER //
mysql> CREATE PROCEDURE whereInDemo(in input varchar(100))
   -> BEGIN
   -> set @Query = 'select Name from DemoTable ';
   -> set @Query = CONCAT(@Query,' where Id IN (',`input`,')');
   -> prepare stmt from @Query;
   -> execute stmt;
   -> deallocate prepare stmt;
   -> END //
Query OK, 0 rows affected (0.23 sec)
mysql> DELIMITER ;

Now you can call stored procedure using CALL command −

mysql> call whereInDemo('100,102');

This will produce the following output −

+-------+
| Name  |
+-------+
| Chris |
| David |
+-------+
2 rows in set (0.04 sec)
Query OK, 0 rows affected, 1 warning (0.07 sec)

Updated on: 28-Feb-2020

800 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements