简体   繁体   English

在SQL Server中插入批量记录

[英]Insert bulk records in SQL Server

Can anybody tell me how to bulk insert data into SQL Server under a transaction? 任何人都可以告诉我如何在事务下批量插入数据到SQL Server? I have a program to import data into multiple tables of a database from a file. 我有一个程序从数据导入数据到数据库的多个表。 I am using SQL Server and Entity Framework to import those records into the database under a transaction. 我正在使用SQL Server和Entity Framework将这些记录导入到事务下的数据库中。 Please tell me is it good way to follow? 请告诉我这是好的方式吗?

I am using Entity Framework for this. 我正在使用Entity Framework。 But when I import 1000 records, I found it causes locks on SQL Server. 但是当我导入1000条记录时,我发现它会导致SQL Server上的锁定。

The file contains many columns. 该文件包含许多列。 Few columns belongs to parent table and the rest of columns belongs to child tables. 很少列属于父表,其余列属于子表。 So how could we map them using SqlBulkCopy ? 那么我们如何使用SqlBulkCopy映射它们呢?

There are 10 child tables. 有10个子表。 I need to insert data from file to child tables first. 我需要先将数据从文件插入子表。 If insertion of records cause error in child table for some what reason I will have to rollback that transaction and continue with another record from file 如果插入记录导致子表中的错误,那么我将不得不回滚该事务并继续从文件中获取另一条记录

Today i found a good library for bulk insert: EntityFrameworkETL 今天我找到了一个很好的批量插入库: EntityFrameworkETL

PM> Install-Package EntityFrameworkETL

Project Description Entity Framework ETL is used to batch commands using an existing DbContext. 项目描述实体框架ETL用于使用现有DbContext批处理命令。 This is useful when moving data between production and development. 在生产和开发之间移动数据时,这非常有用。

Example Usage 示例用法

ETL = new EntityFrameworkETL.ETL(() => new DataContext("name=source"), () => new DataContext("name=target"));
ETL.DeleteAll<Person>();
ETL.BatchInserts<Person>(100, true, x => x.Include("Jobs").Where(y=> y.Age > 65 && y.IsRetired));

This type of operation would work best as a stored procedure. 这种类型的操作最适合作为存储过程。 Otherwise you will multiple back SQL calls. 否则,您将进行多次SQL调用。

Basically you create a stored procedure that accepts a user-defined type, and operate on passed data. 基本上,您创建一个接受用户定义类型的存储过程,并对传递的数据进行操作。

This post has some info on how to do this. 这篇文章有一些关于如何做到这一点的信息。

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

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