A faster solution (no looping, no splitting):
Setup:
DROP PROCEDURE IF EXISTS Spray;
DELIMITER //
CREATE PROCEDURE Spray(IN _table VARCHAR(64),
IN _col VARCHAR(64),
IN _string MEDIUMTEXT)
LANGUAGE SQL
MODIFIES SQL DATA
SQL SECURITY INVOKER
BEGIN
SET @sql = CONCAT('INSERT INTO ', _table,
'(', _col, ')',
' VALUES (', REPLACE(_string, ',', '),(' ), ')'
);
PREPARE _sql FROM @sql;
EXECUTE _sql;
DEALLOCATE PREPARE _sql;
END //
DELIMITER ;
Test:
CREATE TEMPORARY TABLE test_spray (
val INT NOT NULL
);
CALL Spray('test_spray', 'val', "11,22,33,44,55,99999");
SELECT * FROM test_spray;
The table built and the intermediate SQL that populated it:
mysql> SELECT * FROM test_spray;
+-------+
| val |
+-------+
| 11 |
| 22 |
| 33 |
| 44 |
| 55 |
| 99999 |
+-------+
mysql> select @sql;
+---------------------------------------------------------------------+
| @sql |
+---------------------------------------------------------------------+
| INSERT INTO test_spray(val) VALUES (11),(22),(33),(44),(55),(99999) |
+---------------------------------------------------------------------+
The main trick is in the REPLACE
. To break a sentence into words (assuming one space between words), change some datatypes, and change the REPLACE to
REPLACE(_string, ' ', '"),("' )
If _string
might be more than a megabyte long, you will probably need to split it into chunks. Multiple calls to Spray()
will add more rows.
The table could be created with an AUTO_INCREMENT
column, but I don't see any particular need for such.
(I think this technique will work for any versions of MySQL since 4.1, plus MariaDB.)
[Thanks for forcing me to dream up this solution; I have had need for it.]