Exploding UTF-8 Russian (Cyrillic) letters in MySQL

Practice



as is well known, MySQL doesn't have a built-in explode function, but it can be emulated, and with UTF-8 support, meaning it supports Cyrillic - Russian letters

​
CREATE DEFINER=`root`@`%`
FUNCTION `explode`(delimiter VARCHAR(12),string TEXT, indexWord INT)
RETURNS varchar(255) CHARSET utf8mb4
    DETERMINISTIC
RETURN REPLACE(SUBSTRING(SUBSTRING_INDEX(string , delimiter , indexWord ),
       CHAR_LENGTH(SUBSTRING_INDEX(string , delimiter , indexWord -1)) + 1),delimiter , '')

It's very important to use CHAR_LENGTH specifically, instead of LENGTH.

usage example

Exploding UTF-8 Russian (Cyrillic) letters in MySQL

If you need to return many rows (a collection), you can use a function like this

you need to have a table

temp_table_collection(id, one_word) with at least 2 fields, and create a stored function

CREATE DEFINER=`root`@`%` FUNCTION `explode_collection`( list_string TEXT )
RETURNS text CHARSET utf8mb4
DETERMINISTIC
BEGIN
IF list_string = '' THEN RETURN 0; END IF;
SET @cnt=0;
SET @delim=',';
SET @total=LENGTH(list_string ) - LENGTH(REPLACE(list_string ,@delim,''));
WHILE (@cnt<= @total && @total >0) DO
SET @cnt= @cnt+1;
set @text=explode(@delim,list_string ,@cnt);
INSERT INTO temp_table_collection(one_word) VALUES ( @text);

END WHILE;
RETURN @cnt;
END

usage example

SELECT explode_collection(list_words) FROM words limit 1000000;

After running it, each entry after the comma will be inserted into the temporary table temp_table_collection

thanks)

Comments

To leave a comment

If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Lectures and tutorial on "Databases - MySql (Maria DB)"

Terms: Databases - MySql (Maria DB)