MarkMpn / Sql4Cds

SQL 4 CDS core engine and XrmToolbox tool
MIT License
74 stars 22 forks source link

Minimal updates #249

Open MarkMpn opened 2 years ago

MarkMpn commented 2 years ago

Option to only set a field if the new value is different to the existing value, e.g.

accountid name telephone
4d3365e6-62a9-4552-8277-92d7abfb6b47 Data8 NULL
UPDATE account
SET name = 'Data8', telephone1 = '0151 355 4555'
WHERE accountid = '4d3365e6-62a9-4552-8277-92d7abfb6b47'

As the name hasn't changed, the UpdateRequest for this record would only contain the telephone1 field.

nicholas-peterson commented 1 year ago

This would be amazing. I often refer to this as preventing restatements.

sulimanbenhalim commented 1 year ago

Here is a humble thought :

string connectionString = "Your connection string";
using (var ctx = new SqlCDSContext(connectionString))
{
    var updateRequest = new UpdateRequest();
    var columnNames = new List<string>();
    var newValues = new List<object>();
    var tableName = "";
    var whereClause = "";
    //parse the update command
    var match = Regex.Match(updateCommand, @"UPDATE (\w+) SET (.*) WHERE (.*)");
    if (match.Success)
    {
        tableName = match.Groups[1].Value;
        whereClause = match.Groups[3].Value;
        var setClause = match.Groups[2].Value;
        //split the set clause by comma
        var setClauseList = setClause.Split(',');
        foreach (var item in setClauseList)
        {
            //split the item by equal sign
            var columnValue = item.Split('=');
            columnNames.Add(columnValue[0].Trim());
            newValues.Add(columnValue[1].Trim());
        }
    }
    int i = 0;
    while (i < columnNames.Count) 
    {
        var currentValues = connection.QueryFirstOrDefault<Account>(
            "SELECT " + columnNames[i] + " FROM " + tableName + " WHERE " + whereClause);

        if (currentValues.Name != newValues[i])
        {
            updateRequest.Add(columnNames[i], newValues[i]);
        }
        i++;
    }
    ctx.Update(tableName).Set(updateRequest).Where(whereClause).Execute();
}