Skip to content

Instantly share code, notes, and snippets.

@Macagare
Created November 27, 2014 12:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Macagare/fd243befab58f48b366a to your computer and use it in GitHub Desktop.
Save Macagare/fd243befab58f48b366a to your computer and use it in GitHub Desktop.
convert comma separated string into temporary table with individual rows
DROP procedure IF EXISTS split_string;
DELIMITER $$
CREATE PROCEDURE split_string (list TEXT)
BEGIN
DECLARE max INT DEFAULT 0;
DECLARE i INT DEFAULT 1;
DECLARE elem INT DEFAULT 0;
SET max = length(list) - length(replace(list, ',', ''));
WHILE i < max DO
SET elem = SUBSTRING_INDEX(SUBSTRING_INDEX(list, ',', i), ',', -1);
INSERT IGNORE INTO table_destination (target_column) VALUES(elem);
SET i = i + 1;
END WHILE;
END;$$
DELIMITER ;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment