How to split the name string in mysql?

后端 未结 16 2189
轮回少年
轮回少年 2020-11-22 11:44

How to split the name string in mysql ?

E.g.:

name
-----
Sachin ramesh tendulkar
Rahul dravid

Split the name like firstname

16条回答
  •  故里飘歌
    2020-11-22 11:48

    CREATE DEFINER=`root`@`localhost` FUNCTION `getNameInitials`(`fullname` VARCHAR(500), `separator` VARCHAR(1)) RETURNS varchar(70) CHARSET latin1
        DETERMINISTIC
    BEGIN
    DECLARE `result` VARCHAR(500) DEFAULT '';
    DECLARE `position` TINYINT;
    
    
    
    SET `fullname` = TRIM(`fullname`);
    
    SET `position` = LOCATE(`separator`, `fullname`);
    
    IF NOT `position`
    THEN RETURN LEFT(`fullname`,1);
    END IF;
    
    SET `fullname` = CONCAT(`fullname`,`separator`);
    SET `result` = LEFT(`fullname`, 1);
    
    cycle: LOOP
        SET `fullname` = SUBSTR(`fullname`, `position` + 1);
        SET `position` = LOCATE(`separator`, `fullname`);
    
        IF NOT `position` OR NOT LENGTH(`fullname`)
        THEN LEAVE cycle;
        END IF;
    
        SET `result` = CONCAT(`result`,LEFT(`fullname`, 1));
       -- SET `result` = CONCAT_WS(`separator`, `result`, `buffer`);
    END LOOP cycle;
    
    RETURN upper(`result`);
    END
    

    1.Execute this function in mysql. 2.this will create a function. Now you can use this function anywhere you want.

     SELECT `getNameInitials`('Kaleem Ul Hassan', ' ') AS `NameInitials`;
    

    3. The above getNameInitails first parameter is string you want to filter and second is the spectator character on which you want to separate you string. 4. In above example 'Kaleem Ul Hassan' is name and i want to get initials and my separator is space ' '.

提交回复
热议问题