Because the work needs to deal with some comma-delimited string, each time to do is very troublesome, the Internet to find a lot of no ready-made, well, you write a good
1 CREATEDefiner=' Harri ' @ '%`FUNCTION' Substr_for_str ' (' num 'int, `Str`varchar( the))2 RETURNS varchar( -)3 BEGIN4 /*function function: Take a comma-separated string out5 parameter: The index value of the string to be fetched by NUM, starting at 06 Str comma-separated string7 extension: To replace the comma with other matches, you can complete a different delimiter split the string, you may also use the delimiter as a parameter8 */9 SET @substr_for_str =#Routine body goes here ...Ten One SUBSTRING( ASubstring_index (Str,','Num+ 1), - CaseNum - when 0 Then the Char_length ( -Substring_index (Str,',', num) -)+ 1 - ELSE + Char_length ( -Substring_index (Str,',', num) +)+ 2 A END, at CaseNum - when 0 Then - Char_length ( -Substring_index (Str,','Num+ 1) -)-Char_length ( -Substring_index (Str,',', num) in ) - ELSE to Char_length ( +Substring_index (Str,','Num+ 1) -)-Char_length ( theSubstring_index (Str,',', num) *)- 1 $ ENDPanax Notoginseng ); - the + RETURN @substr_for_str; A END;
Test:
Mysql> SELECT str_for_substr (3, ' One,two,three,four,five,six,seven ') as ' value ';
+-------+
| Value |
+-------+
| Four |
+-------+
1 row in Set
MySQL string splitting function