Is there a more efficient way to update the sort order of an entire table?

asp.net-mvc c# dapper sql-server tsql

Question

I'm using client side drag and drop sort ordering for a table of data. The sort order is persisted in the database as a simple integer value. The schema looks like the following:

Id | Title | SortOrder
1  | A     | 0
2  | B     | 1
3  | C     | 2

Data can just be pulled out with a simple ORDER BY and all is well.

The client side drag and drop I've implemented posts an array of the IDs in the new order, which is then persisted to the database using Dapper as follows (removing service layers for brevity):

[HttpPost]
public ActionResult UpdateSort(int[] ids)
{
    if (ids != null && ids.Length > 0)
    {
        using (var con = Connection.OpenSql())
        {
            for (var i = 0; i < ids.Length; ++i)
                con.Execute("UPDATE Table SET SortOrder = @sort WHERE Id = @id", new { sort = i, id = ids[i] });
        }
    }
    return new HttpStatusCodeResult(200);
}

This works fine, but I wondered if there was a better way to handle the update assuming the client side of things can't change. We have one SQL statement being executed per row at the moment, is there any way to keep it parametrized and batch them? Is it possible to remove the loop entirely?

The number of records being used with this code is small, so it's not a huge problem as it is - the question is really just one of curiosity as I couldn't think of a way to easily order some SQL by an arbitrary array of identity values

I hope this question doesn't break site rules - I did have a check and I think it's ok. I also realize the answer may well just be a 'No', but that being the case I'd still be interested in the confirmation.

Accepted Answer

Assuming the Ids wont change , These are the options that i think you have.

Below is the Summary of changes you will need.

  1. Move the update inside a stored procedure.(SP)
  2. As a parameter to the SP either pass in a XML of id's or pass a table type in. (http://msdn.microsoft.com/en-us/library/bb675163(v=vs.110).aspx).

  3. If you are using an xml to pass in the values, Insert the XML entries into table variable.Keep an identity column here so that this will eventually become the sort order.

  4. Join the table you have with the temporary table with the id.

  5. Write an update statement with the Join which basically updates the SortOrder field with IdentityColumn Data.

eg

UPDATE Tab
SET SortOrder = [Idnetityfield]
FROM Table Tab
INNER JOIN TempTable Temp ON Temp.id=Tab.id

I think this is a way in which you can approach your scenario.



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why