所以目前有一些代码是SQL,它返回一个表,其中包含两个表之间的差异。因此它返回一个表,该表只包含两个表之间具有不同数据的行。表格在不同的环境中完全相同。我想知道如何从SQL加载的DataTable中返回包含不同数据的列名?
以下是DataTable填充位置的一小部分:
crs.DataHasChanged = ChangeState.False;
//Compare data of two tables.
sql = "Select 'Source Diff' as CompareDiff, " + BuildColumns(colIncludes, "C1", textColName) + " From " + sourceServer + "." + sourceDB + ".dbo." + tableStateObj.TableName + " C1 ";
sql += "EXCEPT ";
sql += "Select 'Source Diff' as CompareDiff, " + BuildColumns(colIncludes, "C2", textColName) + " From " + destServer + "." + destDB + ".dbo." + tableStateObj.TableName + " C2 ";
sql += "UNION ";
sql += "Select 'Dest Diff' as CompareDiff, " + BuildColumns(colIncludes, "C2", textColName) + " From " + destServer + "." + destDB + ".dbo." + tableStateObj.TableName + " C2 ";
sql += "EXCEPT ";
sql += "Select 'Dest Diff' as CompareDiff, " + BuildColumns(colIncludes, "C1", textColName) + " From " + sourceServer + "." + sourceDB + ".dbo." + tableStateObj.TableName + " C1 ";
sql += "Order By 2,3";
ds = new DataSet();
using (SqlDataAdapter da = new SqlDataAdapter(sql, compareConnString))
{
da.Fill(ds);
}
if (ds.Tables[0].Rows.Count > 0)
{
crs.DataHasChanged = ChangeState.True;
}
crs.DataChangeTable = ds.Tables[0];
答案 0 :(得分:0)
为了知道哪个列不同,您需要仔细阅读它们。好像你有4个工会?比较2列C1和C2。啊。逻辑需要一段时间来弄明白。
-
答案 1 :(得分:0)
下面显示的是帮助我走上正确道路的原因,但这里的代码实际上对我有用:
ds = new DataSet();
using (SqlDataAdapter da = new SqlDataAdapter(sql, compareConnString))
{
da.Fill(ds);
}
if (ds.Tables[0].Rows.Count > 0)
{
int rowCount = ds.Tables[0].Rows.Count;
int rowsRemaining = rowCount;
for (int i = 0; i < rowCount; i+=2)
{
if (!(rowsRemaining == 1))
{
var row1 = ds.Tables[0].Rows[i];
var row2 = ds.Tables[0].Rows[i + 1];
if (row1[1].ToString() == row2[1].ToString())
{
foreach (DataColumn col in ds.Tables[0].Columns)
{
if (col.ColumnName != "CompareDiff")
{
if (row1[col].ToString() != row2[col].ToString())
{
crs.ColumnsChanged.Add(col.ColumnName);
}
}
}
}
}
rowsRemaining -= 2;
}
可能会重构以提高效率,但我现在对结果感到满意。希望这将有助于其他任何有此问题的人。