1

You are provided with a string having delimiters of two types. The schema of the table is provided. How to convert the delimited string into a temporary table in an efficient manner? For example,

Andy~22~US|Jane~24~Australia|Davis~30~UK|Nancy~32~Germany

I am new to MySql. So any help will be greatly appreciated?

Shikhar Maheshwari
  • 399
  • 1
  • 5
  • 16

2 Answers2

0

I would write it like this maybe there is sufficient way with Name , but it has to work!

Create table MIX (
`id` int not null,
`x` text not null)
ENGINE = InnoDB;
insert into mix value (1,'Andy~22~US|Jane~24~Australia|Davis~30~UK|Nancy~32~Germany');
create table unmix select
numbers.n as id,
SUBSTRING_INDEX(SUBSTRING_INDEX(x, '~', 2*numbers.n),'~', -1) as Age,
SUBSTRING_INDEX(SUBSTRING_INDEX(x, '|', 1*numbers.n),'~', -1) as Country,
substring_index(SUBSTRING_INDEX(SUBSTRING_INDEX(x,'~', 2*numbers.n),'|',-1),'~',+1) as Name
from
(select 1 n union all
 select 2 union all 
 select 3 union all select 4 ) 
 numbers INNER JOIN mix
on CHAR_LENGTH(mix.x)
 -CHAR_LENGTH(REPLACE(mix.x, ' ', ''))>=numbers.n-4;
0

Thankfully I wrote a simple code for myself:

DROP procedure IF EXISTS `split_procedure`;

DELIMITER $$

CREATE DEFINER=`cwuser`@`%%` PROCEDURE `split_procedure`(v_stringtosplit text, v_rowdelim CHAR(5), v_coldelim CHAR(5))
BEGIN

SET @replacetosplit := REPLACE(v_stringtosplit, v_rowdelim, '"),("');
SET @replacetosplit := REPLACE(@replacetosplit, v_coldelim, '","');

SET v_stringtosplit = CONCAT(v_rowdelim, v_stringtosplit);

SET @no_of_rows = length(v_stringtosplit) - length(replace(v_stringtosplit, v_rowdelim, ''));
SET @rownum = 1;
SET @no_of_cols = length(v_stringtosplit) - length(replace(v_stringtosplit, v_coldelim, ''));
SET @no_of_cols = (@no_of_cols / @no_of_rows);
SET @colnum = 1;

DROP TABLE IF EXISTS temporary_split_table;

SET @strtabcol = 'CREATE TEMPORARY TABLE temporary_split_table (';
SET @valcol = '';

WHILE(@colnum <= @no_of_cols + 1)
DO
    SET @strtabcol = CONCAT(@strtabcol, 'COL', @colnum, ' VARCHAR(1000)', ',');
    SET @colnum = @colnum + 1;
END WHILE;

SET @strtabcol = CONCAT(LEFT(@strtabcol, LENGTH(@strtabcol)-1), ')');

PREPARE stmt FROM @strtabcol;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @strcol = 'INSERT INTO temporary_split_table VALUES("';

SET @strcol = CONCAT(@strcol, @replacetosplit, '")');
PREPARE stmt FROM @strcol;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SELECT * FROM temporary_split_table;

END$$

DELIMITER ;

Please do not forget to delete the temporary table temporary_split_table after the use of above SP.

The method to call above SP is:

call  split_procedure('Andy~22~US|Jane~24~Australia|Davis~30~UK|Nancy~32~Germany',  '|', '~');
Shikhar Maheshwari
  • 399
  • 1
  • 5
  • 16