How do I bulk insert two datatables that have an Identity relationship

狂风中的少年 提交于 2020-01-25 02:10:06

问题


I'm using SQLBulkCopy, in pseudocode I do this:

  • make new Employee datatable
  • make new EmployeeAddress datatable
  • populate employee table but don't specificy employeeId as it's identity
  • populate EmployeeAddress datatable, but it contains an employeeId field
  • write both datatables to the database by doing this twice and changing the table name:

.

using (var bulk = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.KeepIdentity & SqlBulkCopyOptions.KeepNulls))
    {
        bulk.BatchSize = 25;
        bulk.DestinationTableName = "Employee";
        bulk.WriteToServer(employeeDataTable);
    }       

How can I specify the employeeId in the 2nd datable so that it aligns correctly to the employee that was inserted the first time? The way I read the data is that I read the employee and the address together, so inserting all of the employees then going back and inserting all of the addresses is a bit of a pain.

I was wondering if there was an elegant solution?


回答1:


I'm not too sure how elegant this is, I guess that is up for you to decide. I am assuming you have a unique field or combination of fields that are unique in the employee data.

If you create a staging table on the server, you can bulk insert the data that has all of the employee data as well as the employee address information.

From the staging table, insert the employee data. Then from the staging table join the employee table (to get the newly assigned ids) and insert the employee address data.

Finally drop the staging table.

Everything is still set oriented, so you should have good performance.



来源:https://stackoverflow.com/questions/18513131/how-do-i-bulk-insert-two-datatables-that-have-an-identity-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!