I have this function that creates a table and then receives a CSV File. I need an ID column in it that auto increments which would be used for later use. Therefore I ran the
I suppose you have a table in SQL Server which you created this way:
CREATE TABLE [dbo].[Table1] (
[Column1] INT IDENTITY (1, 1) NOT NULL,
[Column2] NVARCHAR (50) NOT NULL
);
file containing such values:
Column1,Column2
1,N1
2,N2
3,N3
So to bulk insert values to the table you can use SqlBulkCopy this way:
var lines = System.IO.File.ReadAllLines(@"d:\data.txt");
if (lines.Count() == 0) return;
var columns = lines[0].Split(',');
var table = new DataTable();
foreach (var c in columns)
table.Columns.Add(c);
for (int i = 1; i < lines.Count() - 1; i++)
table.Rows.Add(lines[i].Split(','));
var connection = @"your connection string";
var sqlBulk = new SqlBulkCopy(connection);
sqlBulk.DestinationTableName = "Table1";
sqlBulk.WriteToServer(table);