最近,有位朋友遇到这么样的需求:
两个数据库分布在不同的服务器上,都有个CustomerInfo表,要把 A数据库的表中数据导入到B数据库表中,并且B库表中有A的数据记录不能重复导到B中。
实现方法:
一、 建立Linked Server
1.Sql Server建立Linked Server,实现两个异地数据库的链接。
3. 输入远程数据库的登录名和密码
4.点击OK,就链接好了。
二、操作数据库
测试代码如下:
protected void btnImport_Click(object sender, EventArgs e)
{
string connString = "Data Source=.\\sqlexpress;Initial Catalog=TwoDataBase;Integrated Security=true;connection timeout= 60";
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
string sqlstr = "INSERT INTO Twodatabase.dbo.CustomerInfo SELECT * FROM Test.Twodatabase.dbo.CustomerInfo AS TTC WHERE TTC.CustomerID NOT IN(SELECT TwoDataBase.dbo.CustomerInfo.CustomerID FROM TwoDataBase.dbo.CustomerInfo)";
using (SqlCommand cmm = new SqlCommand(sqlstr, conn))
{
cmm.ExecuteNonQuery();
}
}
Response.Write("<Script type='text/javascript'>alert('导入成功')</Script>");
}
{
string connString = "Data Source=.\\sqlexpress;Initial Catalog=TwoDataBase;Integrated Security=true;connection timeout= 60";
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
string sqlstr = "INSERT INTO Twodatabase.dbo.CustomerInfo SELECT * FROM Test.Twodatabase.dbo.CustomerInfo AS TTC WHERE TTC.CustomerID NOT IN(SELECT TwoDataBase.dbo.CustomerInfo.CustomerID FROM TwoDataBase.dbo.CustomerInfo)";
using (SqlCommand cmm = new SqlCommand(sqlstr, conn))
{
cmm.ExecuteNonQuery();
}
}
Response.Write("<Script type='text/javascript'>alert('导入成功')</Script>");
}
注意:
SQL 语句里引用远程数据库中表的方法是:linked Server名.数据库名.dbo.表名
引用主数据库中表的方法是:数据库名.dbo.表名