romanitalian
10/31/2015 - 3:40 PM

mysql_parse_csv

mysql_parse_csv

DELIMITER //

DROP PROCEDURE IF EXISTS explode_table //
CREATE PROCEDURE explode_table(bound VARCHAR(255), startstr INT, endstr INT)

BEGIN
DECLARE id INT DEFAULT 0;
DECLARE value TEXT;
DECLARE occurance INT DEFAULT 0;
DECLARE i INT DEFAULT 0;
DECLARE splitted_value VARCHAR(255);
DECLARE done INT DEFAULT 0;
DECLARE cur1 CURSOR FOR SELECT SUBSTRING(DATA, startstr, endstr) FROM table_name WHERE FILE_NAME LIKE 'some_like_%' LIMIT 1;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

DROP TEMPORARY TABLE IF EXISTS table2;
CREATE TEMPORARY TABLE table2(
    `value` VARCHAR(255) NOT NULL
) ENGINE=Memory;

OPEN cur1;
read_loop: LOOP
FETCH cur1 INTO value;

IF done THEN
LEAVE read_loop;
END IF;

SET occurance = (SELECT LENGTH(value) - LENGTH(REPLACE(value, bound, '')) +1);
SET i=1;
SET id=1;
    WHILE i <= occurance DO
    SET splitted_value = TRIM(
        (SELECT REPLACE(SUBSTRING(SUBSTRING_INDEX(value, bound, i),
            LENGTH(SUBSTRING_INDEX(value, bound, i - 1)) + 1), ';', ''))
    );
    INSERT INTO table2 VALUES (splitted_value);
    SET i = i + 1;
    END WHILE;
END LOOP;

-- return result
SELECT * FROM table2;

CLOSE cur1;
END; //
DELIMITER ;

-- How to use:
CALL explode_table(';', 1, 800);