Search This Blog

Tuesday, September 30, 2014

SqlBulkCopy C# SQL Server import data example

C# > System.Data  > SqlClient > SqlBulkCopy

SqlBulkCopy efficiently bulk load a SQL Server table with data from another source.
The data source is not limited to SQL Server, any data source can be used.
SqlBulkCopy offers a significant performance.






Example:

string sourceConnectionString = "YourSourceConnectionString";
string destinationConnectionString = "YourDestinationConnectionString";

using (SqlConnection sourceConnection =
       new SqlConnection(sourceConnectionString))
            {
                sourceConnection.Open();
                SqlCommand commandSourceData = new SqlCommand(
                    "SELECT * FROM source_table;", sourceConnection);
                SqlDataReader reader = commandSourceData.ExecuteReader();
                using (SqlConnection destinationConnection =
                           new SqlConnection(destinationConnectionString))
                {
                    destinationConnection.Open();
                    using (SqlBulkCopy bulkCopy =
                               new SqlBulkCopy(destinationConnection))
                    {
                        bulkCopy.DestinationTableName = "dbo.destination_table";
                        try
                        {
                            bulkCopy.WriteToServer(reader);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                        }
                        finally
                        {
                            reader.Close();
                        }
                    }
                }

            }