将SQL查询的结果从一个数据库插入到另一个数据库在C# [英] Inserting result of a SQL query from one database to another in C#
问题描述
如何从一个数据库表中获取select语句的结果并将其插入到另一个数据库表中 - 使用C#?
How can I take the result of a select statement from one database table and insert it into another database table - using C#?
问题是我需要使用2个不同的连接字符串在C#代码中。
这是我到目前为止,但isnt工作..
The problem is I need to use 2 different connection strings in the C# code. This is what I have so far but isnt working..
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 server 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();
}
}
问题是我需要在C#代码中使用2个不同的连接字符串。这是我到目前为止,但isnt工作..
The problem is I need to use 2 different connection strings in the C# code. This is what I have so far but isnt working..
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 server 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();
推荐答案
使用 SELECT ... INTO ...
,具有完全限定的表名 database.schema.object_name
,如下所示:
Use SELECT ... INTO ...
with a fully qualified table names database.schema.object_name
, like this:
USE DatabaseName;
SELECT *
FROM DatabaseName.schemaname.Tablename
INSERT INTO AnotherDatabase.schemaname.AnotherTablename;
然后您可以使用ADO.net或其他API从C#执行此查询。
Then you can use ADO.net or other API to execute this query from C#.
这篇关于将SQL查询的结果从一个数据库插入到另一个数据库在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!