DELIMITER $$ USE `test`$$ DROP FUNCTION IF EXISTS `getPY`$$ CREATE DEFINER=`hjd`@`%` FUNCTION `getPY`(in_string VARCHAR(21845)) RETURNS VARCHAR(21845) CHARSET utf8 BEGIN #Intercept the string, the string after each interception is stored in this variable, the initial value is the function parameter in_string DECLARE tmp_str VARCHAR(21845) CHARSET gbk DEFAULT '' ; #Length of tmp_str DECLARE tmp_len SMALLINT DEFAULT 0; #Length of tmp_str DECLARE tmp_loc SMALLINT DEFAULT 0; #Intercept characters, each time the return value of left(tmp_str,1) is stored in this variable DECLARE tmp_char VARCHAR(2) CHARSET gbk DEFAULT ''; #result string DECLARE tmp_rs VARCHAR(21845)CHARSET gbk DEFAULT ''; #Pinyin characters, store the first character of Pinyin corresponding to a single Chinese character DECLARE tmp_cc VARCHAR(2) CHARSET gbk DEFAULT ''; #Initialization, assign in_string to tmp_str SET tmp_str = in_string; #initialize length SET tmp_len = LENGTH(tmp_str); #If the length of the calculated tmp_str is greater than 0, enter the while WHILE tmp_len > 0 DO #Get the first character at the leftmost end of tmp_str. Note that this is to get the first character, which may or may not be Chinese. SET tmp_char = LEFT(tmp_str,1); #The first character on the left is assigned to the pinyin character SET tmp_cc = tmp_char; #Get the position of the encoding range of the character, in order to confirm which one is the first letter of Chinese pinyin SET tmp_loc=INTERVAL(CONV(HEX(tmp_char),16,10),0xB0A1,0xB0C5,0xB2C1,0xB4EE,0xB6EA,0xB7A2,0xB8C1,0xB9FE,0xBBF7,0xBFA6,0xC0AC ,0xC2E8,0xC4C3,0xC5B6,0xC5BE,0xC6DA,0xC8BB,0xC8F6,0xCBFA,0xCDDA ,0xCEF4,0xD1B9,0xD4D1); # Determine whether the first character on the left is a multi-byte or a single-byte character. If it is multi-byte, it is considered a Chinese character and is obtained by the following pinyin. If it is a single-byte character, it will not be processed. If it is a multi-byte character but it is not within the corresponding encoding range, that is, if the corresponding character is not an uppercase letter, it will not be processed, so the number or special character will remain as it is. IF (LENGTH(tmp_char)>1 AND tmp_loc>0 AND tmp_loc<24) THEN #Get the first character of Chinese pinyin SELECT ELT(tmp_loc,'A','B','C','D','E','F','G','H','J','K','L','M','N','O','P','Q','R','S','T','W','X','Y','Z') INTO tmp_cc; END IF; #Concatenate the first character of the pinyin at the left end of the current tmp_str with the returned string SET tmp_rs = CONCAT(tmp_rs,tmp_cc); #Remove the first character from the left end of tmp_str SET tmp_str = SUBSTRING(tmp_str,2); # Calculate the length of the current string SET tmp_len = LENGTH(tmp_str); END WHILE; #return result string RETURN tmp_rs; END$$ DELIMITER ;
https://www.cnblogs.com/godtrue/p/5005770.html