Is there something analogous to a split() method in mySql?

前端 未结 3 371
粉色の甜心
粉色の甜心 2021-01-20 23:54

I\'m looking to write a stored procedure that takes as a parameter a string that\'s delimited by a token and then to run a while loop in the procedure for every item in that str

3条回答
  •  南笙
    南笙 (楼主)
    2021-01-21 00:25

    Unfortunately, mysql doesn't let functions return arrays or tables (that I know of) so you have to do this a bit hackily.

    Here's a sample stored proc:

    DELIMITER $$
    
    create function splitter_count (str varchar(200), delim char(1)) returns int
      return (length(replace(str, delim, concat(delim, ' ')))  - length(str)) $$
    
    CREATE PROCEDURE tokenize (str varchar(200), delim char(1))
    BEGIN
      DECLARE i INT DEFAULT 0;
      create table tokens(val varchar(50));
      WHILE i <= splitter_count(str, delim) DO
        insert into tokens(val) select(substring_index(SUBSTRING_INDEX(str, delim, i+1), delim, -1));
        SET i = i + 1;
      END WHILE;
    
    END $$
    
    DELIMITER ;
    

    This will tokenize your string, and insert the values into a table called "tokens", one token per row. You should be able to modify it to do something useful pretty easily. Also, you may want to increase the input length from 200.

提交回复
热议问题