String split, Token indexing and concatenation (in this order)

All we need is an easy explanation of the problem, so here it is.

How to split the string and create a word with the first character of each token? I use MySQL 5.7 .

CREATE TABLE IF NOT EXISTS t1 (
   id_ INTEGER  NOT NULL,
   value1 INT NOT NULL
INSERT INTO t1 (name) VALUES
('Dummy Gummy 1'), ('Dummy 2'), ('Dummy 3'), ('Dummy 4'),
('Dummy 5'), ('Dummy 6'), ('Dummy 7'), ('Dummy 8')

CREATE TABLE IF NOT EXISTS result (
   id_ INTEGER  NOT NULL,
   value1 INT NOT NULL
INSERT INTO result (new_name) VALUES
('DG1'), ('D2'), ('D3'), ('D4'),
('D5'), ('D6'),('D7'), ('D8')

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Strings are not a strong suit for RDBMS, in your case a function is the best.

Here the rules are simple: split the text, check if it is a number then add the number to the result, if not take the first Letter.

If your rules get more complicated, you have to expand the part after IF item <> '' AND item IS NOT NULL THEN

CREATE TABLE IF NOT EXISTS t1 (
   id_ INTEGER  AUTO_INCREMENT NOT NULL PRIMARY KEY,
   name VARCHAR(100) NOT NULL);
   
INSERT INTO t1 (name) VALUES
('Dummy Gummy 1'), ('Dummy 2'), ('Dummy 3'), ('Dummy 4'),
('Dummy 5'), ('Dummy 6'), ('Dummy 7'), ('Dummy 8')
CREATE Function getfirsst(_text VARCHAR(100))
RETURNS VARCHAR(20)
DETERMINISTIC
BEGIN
DECLARE inipos INTEGER;
DECLARE endpos INTEGER;
DECLARE maxlen INTEGER;
DECLARE item VARCHAR(100);
DECLARE result VARCHAR(100) DEFAULT '';
DECLARE delim VARCHAR(1);

SET delim = ' ';
SET inipos = 1;
SET _text = CONCAT(_text, delim);
SET maxlen = LENGTH(_text);

REPEAT
    SET endpos = LOCATE(delim, _text, inipos);
    SET item =  SUBSTR(_text, inipos, endpos - inipos);
    IF item <> '' AND item IS NOT NULL THEN
        IF item REGEXP '^[0-9]+$' THEN
            SET result :=  CONCAT(result,item);
        ELSE
            SET result :=  CONCAT(result,LEFT(item,1));
        END IF;
        
    END IF;
    SET inipos = endpos + 1;
UNTIL inipos >= maxlen END REPEAT;
RETURN result;
END
SELECT getfirsst(name) FROM t1
| getfirsst(name) |
| :-------------- |
| DG1             |
| D2              |
| D3              |
| D4              |
| D5              |
| D6              |
| D7              |
| D8              |

db<>fiddle here

Method 2

CREATE TABLE IF NOT EXISTS result (
    id_ INTEGER  NOT NULL,
    value1 INT NOT NULL )
SELECT id_, CONCAT(LEFT(value1, 1), id_)
    FROM t1;

(and please provide a PRIMARY KEY)

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply