Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to split CSVs from one column to rows in a new table in MSSQL 2008 R2
    primarykey
    data
    text
    <p>Imagine the following (very bad) table design in MSSQL2008R2:</p> <pre><code>Table "Posts": | Id (PK, int) | DatasourceId (PK, int) | QuotedPostIds (nvarchar(255)) | [...] | 1 | 1 | | [...] | 2 | 1 | 1 | [...] | 2 | 2 | 1 | [...] [...] | 102322 | 2 | 123;45345;4356;76757 | [...] </code></pre> <p>So, the column QuotedPostIds contains a semicolon-separated list of self-referencing PostIds (Kids, don't do that at home!). Since this design is ugly as a hell, I'd like to extract the values from the QuotedPostIds table to a new n:m relationship table like this:</p> <pre><code>Desired new table "QuotedPosts": | QuotingPostId (int) | QuotedPostId (int) | DatasourceId (int) | | 2 | 1 | 1 | | 2 | 1 | 2 | [...] | 102322 | 123 | 2 | | 102322 | 45345 | 2 | | 102322 | 4356 | 2 | | 102322 | 76757 | 2 | </code></pre> <p>The primary key for this table could either be a combination of QuotingPostId, QuotedPostId and DatasourceID or an additional artificial key generated by the database.</p> <p>It is worth noticing that the current Posts table contains about 6,300,000 rows but only about 285,000 of those have a value set in the QuotedPostIds column. Therefore, it might be a good idea to pre-filter those rows. In any case, I'd like to perform the normalization using internal MSSQL functionality only, if possible. </p> <p>I already read other posts regarding this topic which mostly dealt with split functions but neither could I find out how exactly to create the new table and also copying the appropriate value from the Datasource column, nor how to filter the rows to touch accordingly. </p> <p>Thank you!</p> <p><strong>€dit:</strong> I thought it through and finally solved the problem using an external C# program instead of internal MSSQL functionality. Since it seems that it could have been done using Mikael Eriksson's suggestion, I will mark his post as an answer.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload