Home Forums SQL Server 2012 SQL 2012 - General Database import from text/csv file and many to many relationship RE: Database import from text/csv file and many to many relationship

  • I'm assuming that you've already imported the data into a staging or other table. If you're also having problems with the import, we need to know what is being used for the delimiter between the two "columns" is in the file.

    In the meantime, here's a test table. Details are in the comments.

    --===== This would simulate the table that you have the data in.

    -- I'm assuming that you've imported "the file" into such a table.

    -- If you need help with the actual import, we'll need more info about the file.

    -- I've simulated 4 rows but this will quickly work for many, many rows.

    -- This is also the wy you should have posted your data so people can test

    -- their solutions for you. See the first link in my signature line below

    -- for more information on that.

    SELECT d.ArticleID, d.ArticleCategories

    INTO #YourTable

    FROM

    (

    SELECT 5,'1,4,6,7' UNION ALL

    SELECT 6,'8,3,2' UNION ALL

    SELECT 10,'9,2,1,5,2' UNION ALL

    SELECT 1,'4'

    ) d (ArticleID,ArticleCategories)

    ;

    --===== This just shows what the table above looks like.

    SELECT * FROM #Yourtable

    ;

    The solution for this problem is wicked easy if you have a decent, fast splitter. The following code will produce the output you've asked for for all rows. You can store the output in a table or use it as a CTE to join to.

    --===== The solution for this is quite easy with the help

    -- of a decent "splitter" function

    SELECT yt.ArticleID, ArticleCategory = split.Item

    FROM #YourTable yt

    CROSS APPLY dbo.DelimitedSplit8K(ArticleCategories,',') split

    ;

    That's produces the following output from the given data... just like you wanted.

    ArticleID ArticleCategory

    ----------- ---------------

    5 1

    5 4

    5 6

    5 7

    6 8

    6 3

    6 2

    10 9

    10 2

    10 1

    10 5

    10 2

    1 4

    (13 row(s) affected)

    You can get the DelimitedSplit8K function from "RESOURCES" links at the end of the following article...

    http://www.sqlservercentral.com/articles/Tally+Table/72993/

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)