views:

66

answers:

2

I'm doing some data migration from a horribly designed database to a less horribly designed database. There is a many to many relationship that has a primary key in one table that corresponds to a comma separated list in another.

FK_ID | data
-------------
1,2   | foo
3     | bar
1,3,2 | blarg

Is there a way to output the FK_ID field with each comma separated element as a single line in the result set?

result set
FK_ID | data
-------------
1     | foo
2     | foo
3     | bar
1     | blarg
2     | blarg
3     | blarg

I'm thinking this would require some sort of recursive query which I don't think mysql has.

Thanks in advance.

A: 

For me the easiest way to do this would be to write a script that queries the source table and inserts the records into the target table.

Pseudocode:

query = "select * from sourcetable";
get a reader object;
while reading()
{
    orig_FK = reader(FK_ID);
    orig_data = reader(data);
    orig_FK_array = orig_FK split by comma
    foreach(ID in orig_FK_array)
    {
        query = "insert into targettable (ID, data) values (@ID, @Data);";
        add parameters;
        execute query;
    }
}
JYelton
A: 

If you have a Numbers/Tally table, which is a table with a sequential list of integers, you can do it in a single query.

Select Substring(T.FK_ID
   , N.Value
   , CharIndex(',', T.FK_ID + ',', N.Value) - N.Value)
  , T.Data
From Numbers As N
 Cross Join Table As T
Where N.Value <= Len(T.FK_ID)
 And Substring(',' + T.FK_ID, N.Value, 1) = ','
Thomas