簡體   English   中英

使用C#動態將所有表的數據從一個SQL Server數據庫插入第二個數據庫

[英]Insert data from one SQL Server database into a second database for all tables dynamically using C#

我已經使用了這段代碼。 誰能在代碼部分幫助我將數據從一個數據庫移到另一個數據庫?

SqlConnection SourceServerName = new SqlConnection(@"Data Source = Stack; Initial Catalog = SSIS2;Trusted_Connection=yes;");
SqlConnection DestinationServerName = new SqlConnection(@"Data Source = Stack; Initial Catalog = SSIS1;Trusted_Connection=yes;");

SqlCommand Cmd = new SqlCommand("SELECT NAME FROM sys.TABLES", SourceServerName);

SourceServerName.Open();
System.Data.SqlClient.SqlDataReader reader = Cmd.ExecuteReader();

while(reader.Read())
{
    Cmd = new SqlCommand("TRUNCATE TABLE " + reader["name"], DestinationServerName);
    DestinationServerName.Open();
    Cmd.ExecuteNonQuery();

    reader = Cmd.ExecuteReader();

    SqlBulkCopy bulkData = new SqlBulkCopy(DestinationServerName);
    // String Dest = reader["name"].ToString();
    bulkData.DestinationTableName = reader["name"].ToString();
    bulkData.WriteToServer(reader);//reader);
    bulkData.Close();

    DestinationServerName.Close();
}

SourceServerName.Close();

您不能像您一樣重復使用DataReader和SqlCommand。 另外,重用連接可能會讓人頭疼,但是由於您沒有分享創建方式,所以我暫時不做介紹。

// consider wrapping in a using as well
SqlCommand Cmd = new SqlCommand("SELECT NAME FROM sys.TABLES", SourceServerName);
SourceServerName.Open();
System.Data.SqlClient.SqlDataReader reader = Cmd.ExecuteReader();

while(reader.Read())
{
    // create a new command to truncate the table at the destination
    using(var TruncateCmd = new SqlCommand("TRUNCATE TABLE " + reader["name"], DestinationServerName))
    {
        DestinationServerName.Open();
        TruncateCmd.ExecuteNonQuery();
    }
    // sqlbulkcopy is IDisposable, wrap in a using
    using(var SqlBulkCopy bulkData = new SqlBulkCopy(DestinationServerName))
    {
        // have a new SourceCmd to get a DataReader for the source table
        // create a new connection, just to be sure
        using(var SourceCon = new SqlConnection(SourceServerName.ConnectionString))
        using(var SourceCmd = new SqlCommand("select * FROM " + reader["name"], SourceCon))
        {
            SourceCon.Open(); // this is definitely needed
            DestinationServerName.Open(); // not 100% sure if this is needed
            bulkData.DestinationTableName = reader["name"].ToString();
            // WriterToServer knows how to deal with a DataReader
            bulkData.WriteToServer(SourceCmd.ExecuteReader());
        } 
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM