简体   繁体   English

使用Excel中的两个相关表进行批量插入

[英]Bulk inserting with two related tables from Excel

I need to import data from an excel sheet into a database using C# WinForms. 我需要使用C#WinForms将数据从excel工作表导入数据库。 Each row is an 'Electricity Site' with a few columns of data going into the 'Sites' table. 每行都是一个“电力站点”,几行数据进入“站点”表。 Each site also has a 'Contact' with its information (Name, Email, Phone), but that Contact may or may not exist already in the database. 每个站点还具有一个带有其信息(名称,电子邮件,电话)的“联系人”,但是该联系人可能已经存在或可能不存在于数据库中。 That contacts primary key (identity field) is a foreign key in the Sites table but the value is not known at runtime. 联系人主键(标识字段)是Sites表中的外键,但在运行时未知该值。

Here is some of the relevant data that the Excel file contains: 这是Excel文件包含的一些相关数据:

SiteID 网站编号

ContactName 联系人姓名

Email 电子邮件

Phone 电话

Here are the tables: 表格如下:

Contacts
(
    ContactID (identity)
    ContactName
    Email
    Phone 
)

Sites
(
    SiteKey (identity)
    SiteID
    ContactID (foreign key)
)

If that contacts name + email + phone doesnt already exist in the table then it needs to be created and that new identity is needed to be inserted into that row for Sites (if Contact exists already then that ContactID is needed). 如果表中不存在该联系人姓名+电子邮件+电话,则需要创建该联系人,并且需要在该行的网站中插入新的身份(如果联系人已经存在,则需要该ContactID)。

What would be the best way to approach this and get the fastest results. 什么是解决此问题并获得最快结果的最佳方法。 In most cases 1000+ rows are in the Excel sheet. 在大多数情况下,Excel工作表中有1000多个行。

The easiest way is probably to bulkload the two excel files into staging tables with sql bulkcopy and then use a couple of " insert into " statements that lookup the proper foreign key into your real tables. 最简单的方法可能是使用sql bulkcopy将两个excel文件批量加载到临时表中,然后使用几个“ insert into ”语句在实际表中查找正确的外键。

However, since a 1000+ rows is not a lot (depeding on the + of course), so you could just load them both into memory and insert directly with proper keys into your target database. 但是,由于1000+行并不多(当然要在+上减少),因此您可以将它们都加载到内存中,并使用适当的键直接插入目标数据库中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM