1

我在两台不同的服务器上有两个相同的 SQL-Server 数据库,我正在使用以下代码将远程数据库中的一个表中的数据导入本地数据库中的同一个表中。正在正确插入新行。但是,修改后的行没有得到更新。关于我做错了什么的任何线索?

SqlConnection connectionA = new SqlConnection(connectionStringToDatabaseA);
connectionA.Open();

SqlDataAdapter adapterA = new SqlDataAdapter(
    string.Format("select * from MyTable where MyDate='{0}'", today.ToString("yyyy-MM-dd")),
    connectionA);
SqlCommandBuilder commandA = new SqlCommandBuilder(adapterA);
adapterA.MissingSchemaAction = MissingSchemaAction.AddWithKey;
DataSet dataSetA = new DataSet("MyTable");
adapterA.Fill(dataSetA);

DataColumn[] myKey = new DataColumn[2];
myKey[0] = dataSetA.Tables[0].Columns["MyDate"];
myKey[1] = dataSetA.Tables[0].Columns["SequenceNumber"];
dataSetA.Tables[0].Constraints.Clear();
dataSetA.Tables[0].Constraints.Add("myKey", myKey, true);

SqlConnection connectionB = new SqlConnection(connectionStringToDatabaseB);
connectionB.Open();
SqlDataAdapter adapterB = new SqlDataAdapter(
    string.Format("select * from MyTable where DateAbat='{0}'", today.ToString("yyyy-MM-dd")),
    connectionB);
SqlCommandBuilder commandB = new SqlCommandBuilder(adapterB);

adapterB.MissingSchemaAction = MissingSchemaAction.AddWithKey;
DataSet dataSetB = new DataSet("MyTable");
adapterB.Fill(dataSetB);

myKey[0] = dataSetB.Tables[0].Columns["MyDate"];
myKey[1] = dataSetB.Tables[0].Columns["SequenceNumber"];
dataSetB.Tables[0].Constraints.Clear();
dataSetB.Tables[0].Constraints.Add("myKey", myKey, true);

foreach (DataRow dr in dataSetA.Tables[0].Rows)
{
    string sequenceNumber = dr["SequenceNumber"].ToString();
    DataView dv = new DataView(dataSetB.Tables[0], "SequenceNumber=" + sequenceNumber, string.Empty, DataViewRowState.CurrentRows);
    if (dv.Count == 0)
        dr.SetAdded();
    else
        dr.SetModified();
}

dataSetB.Tables[0].Merge(dataSetA.Tables[0], false, MissingSchemaAction.AddWithKey);
adapterB.Update(dataSetB);
4

0 回答 0