5,699,431 members and growing! (18,822 online)
Email Password   helpLost your password?
Database » Database » SQL Server     Intermediate

Application to migrate data between different environments using the ADO.NET 2.0 SqlBulkCopy

By siva pinnaka

This article explains how to migrate data between different SQL Server environments.
SQL, C# 2.0, C#Windows, .NET, .NET 2.0, Win2K, WinXP, Win2003SQL 2000, SQL 2005, VS2005, SQL Server, Visual Studio, DBA, Dev, QA

Posted: 24 Oct 2006
Updated: 30 Nov 2006
Views: 41,192
Bookmarked: 67 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
22 votes for this Article.
Popularity: 5.99 Rating: 4.46 out of 5
3 votes, 13.6%
1
0 votes, 0.0%
2
0 votes, 0.0%
3
2 votes, 9.1%
4
17 votes, 77.3%
5

Introduction

Often need arises to migrate data between different environments for testing or audit purposes. For example, production data can be moved to test environment and this data can be used by testers. This gives a clear idea of how programs behave on actual data volumes. Using this utility, data can be migrated with ease of use. I used SqlBulkCopy of ADO.NET 2.0 for bulk copying data. This managed class provides similar functionality as the BCP utiltity. This program has been used successfully on large volumes of data. It took me approximately 1 hour for loading 8GB of data. More precisely, for loading 1.1 million records, it took 4 minutes and 30 seconds. It supports both SQL 2005 and SQL 2000 Servers. The available features are:

  • Specific tables can be selected for migrating data
  • Deletes existing data in selected tables
  • Reports progress as it loads data
  • Logs results of load or delete operations for every table
  • Can be cancelled in the middle of a process; the application stops loading data after finishing the current table.

Data Migration Screen Shot

Solution walkthrough

This solution contains a C# Windows Forms project. This is a very simple project. A Windows Form does all the work. It uses the BackgroundWorker component to report progress. The source and destination connections are defined in the application configuration file. If any exception happens while deleting or loading data in a table, the application logs the exception and continues to process the next table.

The two main functions in this application are DeleteData and LoadData.

DeleteData

The following tasks are involved in this function:

  • Disable constraints on all tables.
  • Disable triggers on all tables.
  • Delete data from a table (DELETE or TRUNCATE statement used depending on the foreign key constraints on a table). 
  • Log results.
  • Enable constraints on all tables.
  • Enable triggers on all tables.
private void DeleteData()
{
    using (SqlConnection conn = new SqlConnection(strDestConn))
    {
        conn.Open();
        SqlCommand cmd = conn.CreateCommand();
        cmd.CommandTimeout = 0;
        if (ds != null && ds.Tables[0].Rows.Count > 0)
        {
            //Disable Constraints on all tables before deleting data

            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                cmd.CommandText = "ALTER TABLE [" + 
                    dr["TABLE_SCHEMA"].ToString() + "].[" + 
                    dr["TABLE_NAME"].ToString() + 
                    "] NOCHECK CONSTRAINT ALL";
                cmd.CommandText += " ALTER TABLE [" + 
                    dr["TABLE_SCHEMA"].ToString() + "].[" + 
                    dr["TABLE_NAME"].ToString() + 
                    "] DISABLE TRIGGER ALL";
                cmd.ExecuteNonQuery();
            }

            //Delete data in selected tables and log results

            string strLogFile = "DeleteLog" + 
                   DateTime.Now.ToString("MMddyyyyHHmm") + ".txt";
            using (StreamWriter sw = new StreamWriter(strLogFile, false))
            {
                sw.AutoFlush = true;
                foreach (object dr in lstInclude.Items)
                {
                    try
                    {
                        cmd.CommandText = 
                         "SELECT OBJECTPROPERTY ( object_id('" + 
                         dr.ToString() + "'),'TableHasForeignRef')";
                        int intref = Convert.ToInt32(cmd.ExecuteScalar());
                        if (intref == 1)
                            cmd.CommandText = "DELETE FROM " + dr.ToString();
                        else
                            cmd.CommandText = "TRUNCATE TABLE " + 
                                              dr.ToString();
                        cmd.ExecuteNonQuery();

                        sw.WriteLine("Data deleted successfully from " + 
                                     dr.ToString() + " at " + 
                                     DateTime.Now.ToString());
                        sw.WriteLine();
                    }
                    catch (Exception ex)
                    {
                        sw.WriteLine("Error while deleting data" + 
                                     " in table " + dr.ToString() + 
                                     ".Error is " + ex.Message);
                        sw.WriteLine();
                    }
                }
            }

            //Enable Constraints on all tables

            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                cmd.CommandText = "ALTER TABLE [" + 
                    dr["TABLE_SCHEMA"].ToString() + "].[" + 
                    dr["TABLE_NAME"].ToString() + 
                    "] CHECK CONSTRAINT ALL";
                cmd.CommandText += " ALTER TABLE [" + 
                    dr["TABLE_SCHEMA"].ToString() + "].[" + 
                    dr["TABLE_NAME"].ToString() + 
                    "] ENABLE TRIGGER ALL";
                cmd.ExecuteNonQuery();
            }
        }                
    }
}

LoadData

The following tasks are involved in this function:

  • Load data from the source table using a SQL data reader. 
  • Create SqlBulkCopy with KeepIdentity and TableLock options. A lock on the table makes the loading process quicker. By default, SqlBulkCopy disables constraints and triggers on a table while loading data.
  • Map source and table columns. This is necessary if the column ordinal positions are different between the two environments.
  • Eliminate computed columns while mapping columns.
  • Bulk insert data in a table by passing the datareader to SqlBulkCopy.
private void LoadData(string pSourceConn,string pDestConn,string pTable)
{
    using (SqlConnection srcConn = new SqlConnection(pSourceConn))
    {
        string[] strTable = pTable.Split('.');
        //Get data from source table

        srcConn.Open();                
        SqlCommand srcCommand = new SqlCommand("SELECT * FROM " + 
                                pTable, srcConn);
        srcCommand.CommandTimeout = 0;
        SqlDataReader sqldr = srcCommand.ExecuteReader();
        SqlBulkCopy sqlbcp = new SqlBulkCopy(pDestConn,
                             SqlBulkCopyOptions.KeepIdentity | 
                             SqlBulkCopyOptions.TableLock);

        //Map Columns

        SqlConnection destConn = new SqlConnection(pDestConn);
        destConn.Open();
        SqlCommand cmd1 = new SqlCommand("SELECT COLUMN_NAME," + 
                         "COLUMNPROPERTY(OBJECT_ID('" + 
                         strTable[0] +"." +strTable[1]+
                         "'),COLUMN_NAME,'IsComputed')AS 'IsComputed' " + 
                         "FROM INFORMATION_SCHEMA.COLUMNS " + 
                         "WHERE TABLE_SCHEMA = '" + 
                         strTable[0] + "' AND TABLE_NAME = '" + 
                         strTable[1] + "'", destConn);
        SqlDataReader drcolumns = cmd1.ExecuteReader();
        while (drcolumns.Read())
        {
            if(drcolumns.GetInt32(1) != 1)
            sqlbcp.ColumnMappings.Add(drcolumns.GetString(0), 
                                      drcolumns.GetString(0));
        }
        drcolumns.Close();

        //Load Data

        sqlbcp.BulkCopyTimeout = 0;                
        sqlbcp.DestinationTableName = pTable;
        sqlbcp.WriteToServer(sqldr);
        sqldr.Close();
    }
 }

Conclusion

That's all there is to it. I hope this application helps for migrating your data. This can be customized easily if you want to load data from different data sources (e.g.: XML files, flat files...). Thanks for reading. Please provide me feedback about issues or ways to improve.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

siva pinnaka


MCSD.NET Early Achiever,MCDBA SQL 2000,MCITP SQL 2005 Charter Member,MCPD Charter Member
Occupation: Web Developer
Location: United States United States

Other popular Database articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 25 of 50 (Total in Forum: 50) (Refresh)FirstPrevNext
GeneralGreat Application, SivamemberJames Bolles (elpaso)17:23 11 Sep '08  
GeneralEnforce Constraints [modified]memberspoekes0:08 10 Jul '08  
GeneralBackup and restorememberRamsheer Pc21:01 1 Nov '07  
GeneralNice ArticlememberHemant.Kamalakar2:51 22 Oct '07  
GeneralHow can I use SqlBulkCopy to copy data to the local temporary table which is dynamicly generated in a store procedure?memberdddd2186:13 1 Oct '07  
GeneralCollumn Exists in Dest but not Source.membertxghia5810:46 1 Aug '07  
GeneralRe: Collumn Exists in Dest but not Source.membersiva pinnaka6:30 5 Aug '07  
GeneralLife SavermemberJoeIsTheMan13:36 30 Jan '07  
GeneralRe: Life Savermembersiva pinnaka18:10 30 Jan '07  
GeneralUpdate to articlemembersiva pinnaka9:38 1 Dec '06  
GeneralRe: Update to articlememberJeff Firestone6:14 7 Dec '06  
GeneralRe: Update to articlemembersiva pinnaka7:52 7 Dec '06  
QuestionAlso create tables at destination?memberjackmos3:50 21 Nov '06  
AnswerRe: Also create tables at destination?membersiva pinnaka11:38 27 Nov '06  
GeneralThreads?memberxae10:45 19 Nov '06  
GeneralRe: Threads?membersiva pinnaka9:08 20 Nov '06  
GeneralVery good...membervinSharp3:36 15 Nov '06  
GeneralRe: Very good...membersiva pinnaka4:43 15 Nov '06  
GeneralGood...membervinSharp3:35 15 Nov '06  
GeneralHey NicememberKim Alexander9:12 7 Nov '06  
GeneralRe: Hey Nicemembersiva pinnaka10:35 7 Nov '06  
QuestionCan do this with SQL Server 2000 Win CE Edition too?membermimuek4:04 1 Nov '06  
AnswerRe: Can do this with SQL Server 2000 Win CE Edition too?membersiva pinnaka4:49 1 Nov '06  
GeneralSupport for DoubleClicking list itemsmemberJeff Firestone6:56 31 Oct '06  
GeneralRe: Support for DoubleClicking list itemsmembersiva pinnaka8:29 31 Oct '06  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 30 Nov 2006
Editor: Smitha Vijayan
Copyright 2006 by siva pinnaka
Everything else Copyright © CodeProject, 1999-2008
Web18 | Advertise on the Code Project