MySQL String separation by comma operator

后端 未结 2 1651
青春惊慌失措
青春惊慌失措 2021-02-10 04:56

I have String asdasdwdfef,rgrgtggt,weef and i want output like in table format as shown below

id      decription
1       asdasdwdfef
2       rgrgtgg         


        
2条回答
  •  滥情空心
    2021-02-10 05:35

    I got the answer

    First create new function

    CREATE FUNCTION SPLIT_STR(x VARCHAR(255), delim VARCHAR(12), pos INT)
    RETURNS VARCHAR(255)
    RETURN REPLACE(SUBSTRING(SUBSTRING_INDEX(x, delim, pos),
    LENGTH(SUBSTRING_INDEX(x, delim, pos -1)) + 1), delim, '');
    

    Then create stored procedure

    DELIMITER ;;
    CREATE PROCEDURE Split(in fullstr varchar(255))
    BEGIN
        DECLARE a INT Default 0 ;
        DECLARE str VARCHAR(255);
    
        DROP TABLE IF EXISTS my_temp_table;
        CREATE temporary TABLE my_temp_table(ID INT AUTO_INCREMENT NOT NULL, description text, primary key(ID));
    
        simple_loop: LOOP
            SET a=a+1;
            SET str=SPLIT_STR(fullstr,",",a);
            IF str='' THEN
                LEAVE simple_loop;
            END IF;
            #Do Inserts into temp table here with str going into the row
            insert into my_temp_table (description) values (str);
       END LOOP simple_loop;
       select * from my_temp_table;
    END
    

    After that when i call it by call Split('asas,d,sddf,dfd'); it gives me the output that what i want.

    Thanx for every suggestion.

提交回复
热议问题