Created
September 19, 2012 14:29
-
-
Save avoidwork/3749973 to your computer and use it in GitHub Desktop.
MySQL sp_split() splits a comma delimited string into a recordset & inserts it into target table or returns it
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- ---------------------------- | |
-- Procedure structure for `sp_split` | |
-- ---------------------------- | |
DROP PROCEDURE IF EXISTS `sp_split`; | |
delimiter ;; | |
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_split`(IN toSplit text, IN target char(255)) | |
BEGIN | |
# Temp table variables | |
SET @tableName = 'tmpSplit'; | |
SET @fieldName = 'variable'; | |
# Dropping table | |
SET @sql := CONCAT('DROP TABLE IF EXISTS ', @tableName); | |
PREPARE stmt FROM @sql; | |
EXECUTE stmt; | |
DEALLOCATE PREPARE stmt; | |
# Creating table | |
SET @sql := CONCAT('CREATE TEMPORARY TABLE ', @tableName, ' (', @fieldName, ' VARCHAR(1000))'); | |
PREPARE stmt FROM @sql; | |
EXECUTE stmt; | |
DEALLOCATE PREPARE stmt; | |
# Preparing toSplit | |
SET @vars := toSplit; | |
SET @vars := CONCAT("('", REPLACE(@vars, ",", "'),('"), "')"); | |
# Inserting values | |
SET @sql := CONCAT('INSERT INTO ', @tableName, ' VALUES ', @vars); | |
PREPARE stmt FROM @sql; | |
EXECUTE stmt; | |
DEALLOCATE PREPARE stmt; | |
# Returning record set, or inserting into optional target | |
IF target IS NULL THEN | |
SET @sql := CONCAT('SELECT TRIM(`', @fieldName, '`) AS `', @fieldName, '` FROM ', @tableName); | |
ELSE | |
SET @sql := CONCAT('INSERT INTO ', target, ' SELECT TRIM(`', @fieldName, '`) FROM ', @tableName); | |
END IF; | |
PREPARE stmt FROM @sql; | |
EXECUTE stmt; | |
DEALLOCATE PREPARE stmt; | |
END | |
;; | |
delimiter ; |
How to add another column like foreign key?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
THANK YOU. Just spent half an hour trying various options online, and this was the first one that actually compiled and worked straight out of the box. I'm trying to figure out, however, whether or not the results are guaranteed to be in order. I just made a modified version that adds ID as auto_increment, and changes the query out to order by it.
[...]
# Creating table
SET @SQL := CONCAT('CREATE TEMPORARY TABLE ', @tableName, ' (id int not null auto_increment, ', @Fieldname, ' VARCHAR(1000), primary key(id))');
[...]
# Inserting values
SET @SQL := CONCAT('INSERT INTO ', @tableName, '(',@Fieldname ,')',' VALUES ', @vars);
[...]
IF target IS NULL THEN
SET @SQL := CONCAT('SELECT TRIM(
', @fieldName, '
) AS', @fieldName, '
FROM ', @tableName, ' order by id');ELSE
SET @SQL := CONCAT('INSERT INTO ', target, ' SELECT TRIM(
', @fieldName, '
) FROM ', @tableName, ' order by id');END IF;