6

Possible Duplicate:
Can Mysql Split a column ?

I have one string column and one comma separated column as below

Example, I have the table,

Col1 | col2
1    | a,b,c
2    | d,e

From above, I want

Col1,Col2
1   ,a
1   ,b
1   ,c
2   ,d
2   ,e

How to achieve this

It is not the Exact Duplicate.

Community
  • 1
  • 1
StackflowLover
  • 61
  • 1
  • 1
  • 2
  • 3
    Are you sure that you want that comas ? ;) – hsz May 27 '11 at 12:20
  • 3
    Sorry, but I smell bad database design here. You should use a table that looks exactly like your second example (without the commas). – kapa May 27 '11 at 12:22
  • 1
    This column has been asked multiple times on stack overflow. See http://stackoverflow.com/questions/1096679/can-mysql-split-a-column – garnertb May 27 '11 at 12:24
  • @hsz : No need of that commas @ user589983: Could you please provide me the solution in simple way – StackflowLover May 27 '11 at 12:56

1 Answers1

23

You can do this using a stored procedure

DELIMITER $$

CREATE FUNCTION strSplit(x VARCHAR(65000), delim VARCHAR(12), pos INTEGER) 
RETURNS VARCHAR(65000)
BEGIN
  DECLARE output VARCHAR(65000);
  SET output = REPLACE(SUBSTRING(SUBSTRING_INDEX(x, delim, pos)
                 , LENGTH(SUBSTRING_INDEX(x, delim, pos - 1)) + 1)
                 , delim
                 , '');
  IF output = '' THEN SET output = null; END IF;
  RETURN output;
END $$


CREATE PROCEDURE BadTableToGoodTable()
BEGIN
  DECLARE i INTEGER;

  SET i = 1;
  REPEAT
    INSERT INTO GoodTable (col1, col2)
      SELECT col1, strSplit(col2, ',', i) FROM BadTable
      WHERE strSplit(col2, ',', i) IS NOT NULL;
    SET i = i + 1;
    UNTIL ROW_COUNT() = 0
  END REPEAT;
END $$

DELIMITER ;
Johan
  • 74,508
  • 24
  • 191
  • 319