Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat is the best way to fast insert SQL data and dependant rows?
    primarykey
    data
    text
    <p>I need to write some code to insert around 3 million rows of data.<br/> At the same time I need to insert the same number of companion rows.</p> <p>I.e. schema looks like this:</p> <pre><code>Item - Id - Title Property - Id - FK_Item - Value </code></pre> <p>My first attempt was something vaguely like this:</p> <pre><code>BaseDataContext db = new BaseDataContext(); foreach (var value in values) { Item i = new Item() { Title = value["title"]}; ItemProperty ip = new ItemProperty() { Item = i, Value = value["value"]}; db.Items.InsertOnSubmit(i); db.ItemProperties.InsertOnSubmit(ip); } db.SubmitChanges(); </code></pre> <p>Obviously this was terribly slow so I'm now using something like this:</p> <pre><code>BaseDataContext db = new BaseDataContext(); DataTable dt = new DataTable("Item"); dt.Columns.Add("Title", typeof(string)); foreach (var value in values) { DataRow item = dt.NewRow(); item["Title"] = value["title"]; dt.Rows.Add(item); } using (System.Data.SqlClient.SqlBulkCopy sb = new System.Data.SqlClient.SqlBulkCopy(db.Connection.ConnectionString)) { sb.DestinationTableName = "dbo.Item"; sb.ColumnMappings.Add(new SqlBulkCopyColumnMapping("Title", "Title")); sb.WriteToServer(dt); } </code></pre> <p>But this doesn't allow me to add the corresponding 'Property' rows.</p> <p>I'm thinking the best solution might be to add a Stored Procedure like <a href="https://stackoverflow.com/questions/810962/getting-new-ids-after-a-bulk-insert-in-sql-server-2008/810973#810973">this one</a> that generically lets me do a bulk insert (or at least multiple inserts, but I can probably disable logging in the stored procedure somehow for performance) and then returns the corresponding ids.</p> <p>Can anyone think of a better (i.e. more succinct, near equal performance) solution?</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