MySql, split a string and insert into table

后端 未结 4 565
再見小時候
再見小時候 2021-01-04 20:11

I have two inputs for my stored procedure. One is the \'RoledID\' and second one is the \'MenuIDs\'. \'MenusIDs\' is a list of comma separated menus ids that need to be inse

4条回答
  •  孤城傲影
    2021-01-04 20:44

    for this solution, you must create a table with the name split_table, it can have a id(autoincrement) if you need it and must have a column where to store the value (I call it valor)

    DELIMITER $$
    
    USE `dbaname`$$
    
    DROP PROCEDURE IF EXISTS `Split`$$
    
    CREATE DEFINER=`root`@`localhost` PROCEDURE `Split`(
        IN cadena VARCHAR(8000),
        IN delimitador VARCHAR(10)
        )
    BEGIN
    
        TRUNCATE split_table;
    
        SET @posicion = 1;
        SET @ldel = LENGTH(delimitador);     
        SET @valor = SUBSTRING_INDEX(cadena, delimitador, 1);
    
        WHILE @valor <> '' AND @posicion > 0 DO
    
            SET @valor = SUBSTRING_INDEX(cadena, delimitador, 1);
    
            INSERT INTO split_table(valor) VALUES (@valor);
    
            SET @posicion = POSITION(delimitador IN cadena);
            SET @largo = LENGTH(cadena);
    
            IF @largo >= @posicion THEN
                SET cadena = SUBSTR(cadena, @posicion + @ldel, @largo - @posicion);
                SET @valor = SUBSTRING_INDEX(cadena, delimitador, 1);
            ELSE
                SET @posicion = 0;
            END IF;
    
        END WHILE;
    
        END$$
    
    DELIMITER ;
    

提交回复
热议问题