简体   繁体   English

使用linq将数据从一个表复制到另一个表的最快方法

[英]Fastest way to copy data from one table to another using linq

I have a table on another SQL server which I need to copy from overnight. 我在另一台SQL服务器上有一张表,需要隔夜复制。 The structure of the destination table is very similar so I was just going to use something like the code below. 目标表的结构非常相似,因此我将使用下面的代码。 Source - http://forums.asp.net/t/1322979.aspx/1 来源-http://forums.asp.net/t/1322979.aspx/1

I have not tried this yet, but is there a better/quicker way to do this in linq? 我还没有尝试过,但是在linq中有没有更好/更快的方法可以做到这一点?

    //there exist two table list and listSecond
    DataClassesDataContext dataClass = new DataClassesDataContext(); //create the instance of the DataContext

    var str = from a in dataClass.lists select a;
    foreach (var val in str) // iterator the data from the list and insert them into the listSecond
    {
        listSecond ls = new listSecond();
        ls.ID = val.ID;
        ls.pid = val.pid;
        ls.url = val.url;
        dataClass.listSeconds.InsertOnSubmit(ls);

    }
    dataClass.SubmitChanges();
    Response.Write("success");

Using LINQ to insert large amounts of data is not a good idea, except maybe with complicated schemas that need much transformations before being copied. 使用LINQ插入大量数据不是一个好主意,除非是复杂的架构,在复制之前需要进行大量转换。 It will create a separate query for each row inserted, in addition to logging them all in the transaction log. 除了将所有记录都记录在事务日志中之外,它将为插入的每一行创建一个单独的查询。

A much faster solution can be found here - it's using SqlBulkCopy , which is a method for inserting large amounts of data in a single query, withouth transaction logging to slow it down. 这里可以找到一个更快的解决方案-它使用SqlBulkCopy ,这是一种在单个查询中插入大量数据的方法,而无需进行事务日志记录来降低其速度。 It will be an order of magnitude faster, and I'm telling you this from personal experience with both methods. 这将快一个数量级 ,而我是通过两种方法的亲身经验告诉您的。

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

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