简体   繁体   English

使用SQLBulkCopy插入相关表

[英]Using SQLBulkCopy to Insert into Related Tables

I am using SQL Bulk copy to read data form Excel to SQL DB. 我正在使用SQL批量复制从Excel读取数据到SQL DB。 In the Database, I have two tables into which I need to insert this data from Excel. 在数据库中,我有两个表需要从Excel中插入此数据。 Table A and Table B which uses the ID(primary Key IDENTITY) from Table A to insert corresponding row records into Table B . Table ATable B ,它使用从ID(主键IDENTITY) Table A来插入相应的行记录到Table B
I am able to insert into one table ( Table A ) using the following Code. 我可以使用以下代码插入一个表( Table A )中。

using (SqlConnection connection = new SqlConnection(strConnection)) {
    connection.Open();
    using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection)) {
        bulkCopy.DestinationTableName = "dbo.[EMPLOYEEINFO]";
        try {
            // Write from the source to the destination.
            SqlBulkCopyColumnMapping NameMap = new SqlBulkCopyColumnMapping(data.Columns[0].ColumnName, "EmployeeName");
            SqlBulkCopyColumnMapping GMap = new SqlBulkCopyColumnMapping(data.Columns[1].ColumnName, "Gender");
            SqlBulkCopyColumnMapping CMap = new SqlBulkCopyColumnMapping(data.Columns[2].ColumnName, "City");
            SqlBulkCopyColumnMapping AMap = new SqlBulkCopyColumnMapping(data.Columns[3].ColumnName, "HomeAddress");

            bulkCopy.ColumnMappings.Add(NameMap);
            bulkCopy.ColumnMappings.Add(GMap);
            bulkCopy.ColumnMappings.Add(CMap);
            bulkCopy.ColumnMappings.Add(AMap);

            bulkCopy.WriteToServer(data);
        }
        catch (Exception ex) {
            Console.WriteLine(ex.Message);
        }
    }
}

But then I am not sure how to extend it for two tables which are bound by Foreign Key relationship.Especially, Table B uses the Identity value from Table A Any example would be great. 但是然后我不确定如何将其扩展到受外键关系约束的两个表中。特别是Table B使用Table A的Identity值。任何示例都很好。 I googled it and none of the threads on SO couldn't give a Working example. 我用谷歌搜索,所以没有一个线程不能给出工作示例。

AFAIK bulk copy can only be used to upload into a single table. AFAIK批量复制只能用于上传到单个表中。 In order to achieve a bulk upload into two tables, you will therefore need two bulk uploads. 为了实现批量上传到两个表中,因此需要两个批量上传。 Your problem comes from using a foreign key which is an identity. 您的问题来自使用作为身份的外键。 You can work around this, however. 但是,您可以解决此问题。 I am pretty sure that bulk copy uploads sequentially, which means that if you upload 1,000 records and the last record gets an ID of 10,197, then the ID of the first record is 9,198! 我很确定批量复制是按顺序上传的,这意味着如果您上传1,000条记录,而最后一条记录的ID为10,197,则第一条记录的ID为9,198! So my recommendation would be to upload your first table, check the max id after the upload, deduct the number of records and work from there! 因此,我的建议是上传您的第一个表,检查上传后的最大ID,从中扣除记录数并开始工作!

Of course in a high use database, someone might insert after you, so you would need to get the top id by selecting the record which matches your last one by other details (assuming a combination of (upto) all fields would be guaranteed to be unique). 当然,在高使用率的数据库中,可能有人会在您之后插入,因此您需要通过选择与其他记录相匹配的最后一条记录来获取最上面的ID(假设将(最多)所有字段组合在一起)独特)。 Only you know if this is likely to be a problem. 只有您知道这是否可能是一个问题。

The alternative is not to use an identity column in the first place, but I presume you have no control over the design? 替代方案不是首先使用标识列,但我想您无法控制设计? In my younger days, I made the mistake of using identities, I never do now. 在我年轻的时候,我犯了使用身份的错误,我从不这样做。 They always find a way of coming back to bite! 他们总是找到一种重新咬人的方法!

For example to add the second data: 例如添加第二个数据:

DataTable secondTable = new DataTable("SecondTable");
secondTable.Columns.Add("ForeignKey", typeof(int));
secondTable.Columns.Add("DataField", typeof(yourDataType));

... ...

Add data to secondTable. 将数据添加到secondTable。

(Depends on format of second data) (取决于第二数据的格式)

int cnt = 0;
foreach (var d in mySecondData)
{
    DataRow newRow = secondTable.NewRow();
    newRow["ForeignKey"] = cnt;
    newRow["DataField"] = d.YourData;
    secondTable.Rows.Add(newRow);
}

Then after you found out the starting identity (int startID). 然后找到起始身份(int startID)。

for (int i = 0; i < secondTable.Rows.Count; i++)
{
    secondTable["ForeignKey"] = secondTable["ForeignKey"] + startID;
}

Finally: 最后:

bulkCopy.DestinationTableName = "YourSecondTable";
bulkCopy.WriteToServer(secondTable);

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

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