A Little Noise

November 20, 2009

GROUP UNCONCAT

Filed under: MySQL — snoyes @ 3:18 pm

Dunno why you’d rather do this in SQL than in your application layer, but if you do, here’s one way to turn a delimited string of values back into multiple rows – just the opposite of GROUP_CONCAT:

SET @sourceString = 'a,b,c,d,e';
SET @sql = CONCAT('INSERT INTO t VALUES (\\'', REPLACE(@sourceString, ',', '\\'),(\\''), '\\')');
PREPARE myStmt FROM @sql;
EXECUTE myStmt;

Just to show what’s going on:

mysql> SELECT @sql;
+----------------------------------------------------+
| @sql                                               |
+----------------------------------------------------+
| INSERT INTO t VALUES ('a'),('b'),('c'),('d'),('e') |
+----------------------------------------------------+

1 Comment »

  1. REPLACE(@sourceString, ‘,’, ‘\\’),(\\”), ‘\\’)’)…
    error :-Missing Paranthesis
    tell solution

    Comment by SUNNY VERMA — March 20, 2019 @ 2:15 am

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress