Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Minimal updates #249

Closed
MarkMpn opened this issue Sep 28, 2022 · 2 comments · Fixed by #571
Closed

Minimal updates #249

MarkMpn opened this issue Sep 28, 2022 · 2 comments · Fixed by #571

Comments

@MarkMpn
Copy link
Owner

MarkMpn commented Sep 28, 2022

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
Copy link

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

@sulimanbenhalim
Copy link

sulimanbenhalim commented Jan 21, 2023

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();
}

@MarkMpn MarkMpn linked a pull request Nov 3, 2024 that will close this issue
@MarkMpn MarkMpn closed this as completed in 5026771 Nov 4, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants