Split a string and insert it as individual values into a MySQL table?

MySQLMySQLi Database

You can achieve this with the help of prepared statement in MySQL. First you need to create a table. The query to create a table is as follows

mysql> create table University
   - > (
   - > UserId int,
   - > UniversityId int
   - > );
Query OK, 0 rows affected (0.64 sec)

At first, let us set values in the above-mentioned columns. Here, we have set a string with comma separated value for UserId column. We will split this and insert in the table

mysql> SET @userId = '8,9,10';
Query OK, 0 rows affected (0.00 sec)
mysql> SET @UniversityId = 100;
Query OK, 0 rows affected (0.00 sec)
mysql> SET @myValues = REPLACE(@userId, ',', CONCAT(', ', @UniversityId, '),('));
Query OK, 0 rows affected (0.00 sec)
mysql> SET @myValues = CONCAT('(', @myValues, ', ', @UniversityId, ')');
Query OK, 0 rows affected (0.00 sec)
mysql> SET @insertQuery1 = CONCAT('INSERT INTO University VALUES', @myValues);
Query OK, 0 rows affected (0.00 sec)

After implementing all the steps, you need to execute the above mentioned @insertQuery1.

The query is as follows

mysql> PREPARE st FROM @insertQuery1;
Query OK, 0 rows affected (0.00 sec)
Statement prepared
mysql> EXECUTE st;
Query OK, 3 rows affected (0.18 sec)
Records: 3 Duplicates: 0 Warnings: 0

Now display all records from the table using select statement

mysql> select *from University;

The following is the output displaying that we have successfully split the string (8, 9, 10) and inserted them as individual values

+--------+--------------+
| UserId | UniversityId |
+--------+--------------+
|      8 |          100 |
|      9 |          100 |
|     10 |          100 |
+--------+--------------+
3 rows in set (0.00 sec)

Now deallocate the prepared statement.

The query is as follows

mysql> DEALLOCATE PREPARE st;
Query OK, 0 rows affected (0.00 sec)
raja
Published on 19-Mar-2019 12:24:59
Advertisements