-2

I have code in a C# application that transfers specific records from a table to another table but my first table has about 28000 records and it takes a lot of time to transfer it to the second table...
What is the best way to perform this transfer?
Here is my complete code:

private void btnsend_Click (object sender, EventArgs e)
{
    List<QC> lstQc = new List<QC>();
    lstQc = db.QCs.ToList();

    foreach (var temp in lstQc)
    {
        TEST_PACKAGE objtestpackage = new TEST_PACKAGE();

        if (temp.Package != "")
        {
            objtestpackage.DocumentNO = temp.Document_No;

            if (temp.UNIT != "")
            {
                objtestpackage.Unit = Convert.ToInt32(temp.UNIT);
            }

            objtestpackage.Test_Package___No = temp.Package;
            db.TEST_PACKAGE.Add(objtestpackage);
            db.SaveChanges();
         }
     }

    MessageBox.Show("tarnsfer info to test package succsefully!");
}
bummi
  • 27,123
  • 14
  • 62
  • 101
nafas smaily
  • 25
  • 1
  • 4
  • 9
    99 times out of 100, you don't actually need to use a cursor..... – Mitch Wheat Dec 10 '14 at 06:00
  • plain old sql: insert table1 select field1, field2, field3 from table2. you can pack that in a SP and then execute it from your c# code. – gsharp Dec 10 '14 at 07:12

2 Answers2

0

You can use plain ADO.NET and use SqlBulkCopy, this is the example from the SqlBulkCopy documentation which will be much much faster than copy them one by one:

using System.Data.SqlClient;

class Program
{
    static void Main()
    {
        string connectionString = GetConnectionString();
        // Open a sourceConnection to the AdventureWorks database. 
        using (SqlConnection sourceConnection =
                   new SqlConnection(connectionString))
        {
            sourceConnection.Open();

            // Perform an initial count on the destination table.
            SqlCommand commandRowCount = new SqlCommand(
                "SELECT COUNT(*) FROM " +
                "dbo.BulkCopyDemoMatchingColumns;",
                sourceConnection);
            long countStart = System.Convert.ToInt32(
                commandRowCount.ExecuteScalar());
            Console.WriteLine("Starting row count = {0}", countStart);

            // Get data from the source table as a SqlDataReader.
            SqlCommand commandSourceData = new SqlCommand(
                "SELECT ProductID, Name, " +
                "ProductNumber " +
                "FROM Production.Product;", sourceConnection);
            SqlDataReader reader =
                commandSourceData.ExecuteReader();

            // Open the destination connection. In the real world you would  
            // not use SqlBulkCopy to move data from one table to the other  
            // in the same database. This is for demonstration purposes only. 
            using (SqlConnection destinationConnection =
                       new SqlConnection(connectionString))
            {
                destinationConnection.Open();

                // Set up the bulk copy object.  
                // Note that the column positions in the source 
                // data reader match the column positions in  
                // the destination table so there is no need to 
                // map columns. 
                using (SqlBulkCopy bulkCopy =
                           new SqlBulkCopy(destinationConnection))
                {
                    bulkCopy.DestinationTableName =
                        "dbo.BulkCopyDemoMatchingColumns";

                    try
                    {
                        // Write from the source to the destination.
                        bulkCopy.WriteToServer(reader);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                    finally
                    {
                        // Close the SqlDataReader. The SqlBulkCopy 
                        // object is automatically closed at the end 
                        // of the using block.
                        reader.Close();
                    }
                }

                // Perform a final count on the destination  
                // table to see how many rows were added. 
                long countEnd = System.Convert.ToInt32(
                    commandRowCount.ExecuteScalar());
                Console.WriteLine("Ending row count = {0}", countEnd);
                Console.WriteLine("{0} rows were added.", countEnd - countStart);
                Console.WriteLine("Press Enter to finish.");
                Console.ReadLine();
            }
        }
    }

    private static string GetConnectionString()
        // To avoid storing the sourceConnection string in your code,  
        // you can retrieve it from a configuration file. 
    {
        return "Data Source=(local); " +
            " Integrated Security=true;" +
            "Initial Catalog=AdventureWorks;";
    }
}
Omar.Alani
  • 4,050
  • 2
  • 20
  • 31
0

You can have a stored procedure which accepts the list of primary keys to indentify the records needs to be transferred. You can get the records from Table A and insert into Table B from same procedure.

Call this stored procedure from C# code. This will be much faster then transferring records from C#.

Here's how to pass list to stored procedure: How to pass an array into a SQL Server stored procedure

Also you can pass the comma saperated PK string as a parameter and split in stored procedure.

Community
  • 1
  • 1
SiD
  • 511
  • 4
  • 15