在sql服务器之间复制数据库

时间:2011-11-17 11:44:18

标签: c# asp.net sql-server-2005

我正在开发一个用于在SQL Server之间复制数据的Web应用程序。该工具将允许您指定要从哪个服务器复制,然后将从源服务器复制到目标服务器的特定数据库(始终具有相同的名称)。

这样做的最佳方法是什么?数据可能非常大,因此也需要考虑速度。


我的尝试是尝试运行我使用SQL Server Management Studio创建的SSIS包。包裹存储在本地。

计划是修改源和目标连接字符串并启动程序包。

这是我的代码:

public void DataTransfer(String sourceConnection, String destConnection, String pkgLocation)
{
        Package pkg;
        Application app;
        DTSExecResult pkgResults;

        try
        {
            app = new Application();
            pkg = app.LoadPackage(pkgLocation, null);

            foreach (ConnectionManager connectionManager in pkg.Connections)
            {
                SqlConnectionStringBuilder builder;
                switch (connectionManager.Name)
                {
                    case "SourceConnection":
                        builder = new SqlConnectionStringBuilder(sourceConnection);
                        builder.Remove("Initial Catalog");
                        builder.Add("Initial Catalog", "StagingArea");
                        var sourceCon = builder.ConnectionString + ";Provider=SQLNCLI;Auto Translate=false;";
                        //Added spaces to retain password!!!
                        sourceCon = sourceCon.Replace(";", "; ");
                        connectionManager.ConnectionString = sourceCon;
                        Debug.WriteLine(connectionManager.ConnectionString.ToString());
                        break;
                    case "DestinationConnection":
                        builder = new SqlConnectionStringBuilder(destConnection);
                        builder.Remove("Initial Catalog");
                        builder.Add("Initial Catalog", "StagingArea");
                        var destCon = builder.ConnectionString + ";Provider=SQLNCLI;Auto Translate=false;";
                        //Added spaces to retain password!!!
                        destCon = destCon.Replace(";", "; ");
                        connectionManager.ConnectionString = destCon;
                        Debug.WriteLine(connectionManager.ConnectionString.ToString());
                        break;
                }
            }
            pkgResults = pkg.Execute();
        }
        catch (Exception e)
        {

            throw;
        }

        Debug.WriteLine(pkgResults.ToString());
}

执行pkg时,我会遇到以下例外情况:

A first chance exception of type 'System.Runtime.InteropServices.COMException' occurred in Microsoft.SqlServer.ManagedDTS.dll
A first chance exception of type 'Microsoft.SqlServer.Dts.Runtime.DtsComponentException' occurred in Microsoft.SqlServer.ManagedDTS.dll

我不确定从哪里开始,有什么想法?

1 个答案:

答案 0 :(得分:1)

我会写一个SSIS包进行数据复制/转换,网站只需配置连接字符串并启动包。