0

I have a CSV file that contains 10 columns. I want to save 5 columns in one SQL table and next 5 columns in the second SQL table using C#

Cptmaxon
  • 505
  • 2
  • 12
DonboscoJ
  • 9
  • 1
  • why not use a library like in this [question](http://stackoverflow.com/questions/2081418/parsing-csv-files-in-c-sharp) also your question needs a lot more info like what DB adapter are you using? and how is this related to asp.net? – Cptmaxon Feb 02 '16 at 11:14
  • Please go through this link , this will change Csv data to .net Datatable class http://www.codeproject.com/Articles/11698/A-Portable-and-Efficient-Generic-Parser-for-Flat-F – vikas singh aswal Feb 02 '16 at 11:16

1 Answers1

1

I think the easiest (and probably one of the fastest) ways for this is to do is using a temporary table.

Assuming the following CSV file:

Column1,Column2,Column3,Column4,Column5,Column6,Column7,Column8,Column9,Column10
Row1Value1,Value2,Value3,Value4,Value5,Value6,Value7,Value8,Value9,Value10
Row2Value1,Value2,Value3,Value4,Value5,Value6,Value7,Value8,Value9,Value10
...

Use something like this (in your C#) to import the file into de DB, where you can influence the file-path:

    CREATE TABLE #temp( column1 varchar,
                        column2 varchar,
                        column3 varchar,
                        column4 varchar,
                        column5 varchar,
                        column6 varchar,
                        column7 varchar,
                        column8 varchar,
                        column9 varchar,
                        column10 varchar);

    BULK INSERT #temp1
       FROM 'C:\Test.csv'
       WITH (
             FIELDTERMINATOR =',',
             ROWTERMINATOR = '\ n',
             FIRSTROW = 2
          )

Now you can use INSERT INTO SELECT to select columns into you other tables:

    INSERT INTO table1
    (Id, Name, Title, Desription, Date)
    SELECT column1, column3, column5, column7, column10
    FROM #temp1;

    INSERT INTO table2
    (SupplierName, Country, Contact, Addres, City)
    SELECT column2, column4, column6, column8, column9
    FROM #temp1;

If you like you can DROP or EMPTY the #temp1 table now.

Jeroen Bouman
  • 771
  • 9
  • 15