-
-
Save avoidwork/3749973 to your computer and use it in GitHub Desktop.
-- ---------------------------- | |
-- 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 ; |
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;
How to add another column like foreign key?
if i have text with comma and i want to insert to columns table with the number of the comma in the text