比较两行并使用c#和sql更新列值是否更改

时间:2017-04-13 04:23:20

标签: c# sql-server datatable compare

我正在创建一个关于同步数据库数据的应用程序。

我有一个源数据库和一个目标数据库(它是空的)。

当应用程序运行时,它会在目标数据库的表中创建相同的列,并另外添加UpdateYN列。

然后它将源DB表中的数据插入到目标DB的表中。

这意味着除了UpdateYN列之外,两个表具有相同的数据。

我已经在上面构建了一个代码。但现在我想这样做。

当我更新Source DB的表列时,我只想更新目标DB表中的那一行。

因此,在更新之前,需要比较两行,并检查值,但我不知道如何处理它。

请给我一些关于此的链接或分享您的知识,谢谢。

代码如下。

注意:源表列名称不是固定值

DataTable DeptDt = null; 

// Get Source DB table
DeptDt = DataSetMaker.Instance.FromMsSql(SourceDBPath, SourceDBName, SourceDBLoginID, SourceDBLoginPass, SourceDBDeptTableName);

if (DeptDt != null)
{
    Tool.Log(LogKinds.DEPT, LogLevels.INFORMATION, SourceKind, "Starting Dept Sync");
    if (DeptDt.Rows.Count == 0)
    {
        Tool.Log(LogKinds.DEPT, LogLevels.WARNNING, SourceKind, "There`s no Dept Datas.");
    }
    else
    {
        // PK of Source Table
        string DeptPk = AppConfigHelper.GetAppString(Words.SourceDeptPKColumn);

        // add @ like @deptcode
        string DeptPkVar = Util.ColNameToVarName(DeptPk);

        // wrapped like [deptcode]
        DeptPk = Util.GetActualColName(DeptPk);
        List<string> ErrorPks = Tool.GetSyncErrorPks(LogKinds.DEPT, LogSections.SOURCE);

        foreach (DataRow row in DeptDt.Rows)
        {
            string pk = row[DeptPk] + "";

            if (IsOnlyErrorSync && !ErrorPks.Contains(pk))
            {
                continue;
            }

            try
            {
                List<SqlParameter> pms = new List<SqlParameter>();

                // Add all Source table's columns to pms
                foreach (DataColumn item in DeptDt.Columns)
                {
                    var sp = new SqlParameter("@" + item.ColumnName, row[item.ColumnName]);
                    pms.Add(sp);
                }

                // Update and insert rows to Target Table. method is below 
                // ShadowDeptTable is Target Table
                QueryHelper.InsertOrUpdateShadowTables(Words.ShadowDeptTable,
                    new SqlParameter[]{new SqlParameter(DeptPkVar,pk)}, pms.ToArray());
            }
            catch (Exception ex)
            {
                Tool.SetSyncError(pk, LogKinds.DEPT, LogSections.SOURCE, ex.ToString());
            }
        }

        if (IsOnlyErrorSync)
        {
            Tool.ClearSyncError(LogKinds.DEPT, LogSections.SOURCE);
        }

        Tool.Log(LogKinds.DEPT, LogLevels.INFORMATION, SourceKind,"Dept Sync completed.");
    }
}
else
{
    Tool.ErrorLog(LogKinds.DEPT, LogSections.SOURCE, SourceKind, " Dept sync was failed");
}

public static int InsertOrUpdateShadowTables(string table, SqlParameter[] keys, params SqlParameter[] pms)
{
    int st = 0;

    // Count Target tables rows by PK - To check that row is exist in Target Table
    StringBuilder sb = new StringBuilder(string.Format("select count(*) from {0} ", table));
    string where = string.Empty;

    if (keys.Length > 0)
    {
        where += " where ";
        var temp = keys.Select(a => "[" + a.ParameterName.Substring(1, a.ParameterName.Length - 1) + "]"
         + " = '" + a.Value + "'").ToArray();
        where += string.Join(" and ", temp);
    }

    sb = sb.Append(where);

    // get connection string of target table
    string constr = Util.GetPropVal(Words.PropConnectionString);

    // count target table's rows 
    var obj = SqlHelper.ExecuteScalar(constr, CommandType.Text, sb.ToString(), keys);
    int cnt = Convert.ToInt32(obj);
    sb = sb.Clear();

    // insert 
    sb = sb.Append("insert into " + table + "(");
    string cols = null;
    string vals = null;

    List<SqlParameter> pmlist = new List<SqlParameter>(keys);
    pmlist.AddRange(pms);

    var merged = keys.Union(pmlist).GroupBy(p => p.ParameterName).Select(e => e.First());
    cols = string.Join(",",
           merged.Select(a =>
          "[" + a.ParameterName.Substring(1, a.ParameterName.Length - 1) + "]"));
    vals = string.Join(",",
                merged.Select(a => "'" + a.Value + "'"));
    sb = sb.Append(cols);
    sb = sb.Append(") values(");
    sb = sb.Append(vals);
    sb = sb.Append(")");

    // Update rows(the row exists in Target table)
    if (cnt > 0)
    {
        sb = sb.Clear();
        sb = sb.Append("update " + table + " set ");
        sb = sb.Append(string.Join(",", pms.Select(a =>
              "[" + a.ParameterName.Substring(1, a.ParameterName.Length - 1) + "]" + " = "
                 + "'" + a.Value + "'")));
        sb = sb.Append(where);

        // Update query excutes here
        obj = SqlHelper.ExecuteScalar(constr, CommandType.Text, sb.ToString());

        // Set UpdateYN = U
        sb = sb.Clear();
        sb = sb.Append("update " + table + " set [UpdateYN] = 'U'");
        sb = sb.Append(where);

        obj = SqlHelper.ExecuteScalar(constr, CommandType.Text, sb.ToString());
    }
    // Insert rows
    else
    {
        // Insert query executes here
        obj = SqlHelper.ExecuteScalar(constr, CommandType.Text, sb.ToString());

        // set UpdateYN = I
        sb = sb.Clear();
        sb = sb.Append("update " + table + " set [UpdateYN] = 'I'");
        sb = sb.Append(where);
        obj = SqlHelper.ExecuteScalar(constr, CommandType.Text, sb.ToString());
    }

    return Convert.ToInt32(obj);
}

0 个答案:

没有答案