1

如何连接来自一个数据库的查询结果并将其插入 ac# 应用程序中的另一个?

这是我到目前为止所拥有的,但它不起作用。

// select from first database
string sCMD_All = "SELECT * FROM table";
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();

using (SqlConnection myConn = new SqlConnection(ConnectionString))
{
    using (SqlCommand myCommand = new SqlCommand(sCMD_All, myConn))
    {
        myConn.Open();
        SqlDataReader reader = myCommand.ExecuteReader();
        da.Fill(ds);
        myConn.Close();
    }
}
DataTable sqTable = ds.Tables[0];

//insert into 2nd database
DataTable newTable = new DataTable();
newTable = sqTable;
using (SqlConnection myConn = new SqlConnection(ConnectionString_M))
{
    string sCMD_I = "INSERT INTO tableNew @newTable";

    using (SqlCommand myCommand = new SqlCommand(sCMD_I, myConn))
    {
        myConn.Open();
        SqlDataReader reader = myCommand.ExecuteReader();
        myConn.Close();
    }
}
4

1 回答 1

0
var commandText = 
    @"insert into [server].[database2].[schema].[table] (col1, col2, ...)
    select col1, col2, ... from [server].[database1].[schema].[table]";

using (var connection = new SqlConnection(connectionString))
{
    using (var command = new SqlCommand(commandText, connection))
    {
        connection.Open();
        command.ExecuteNonQuery();
    }
}

注意:如果数据库位于不同的服务器上,您应该链接服务器:

exec sp_addlinkedserver @server = 'server2'

于 2013-02-04T14:41:16.510 回答