ORM or something to handle SQL tables with an order column efficiently

旧街凉风 提交于 2019-11-30 15:06:46

My advice is to do two things:

  1. Choose very large increments between your items, say one million. This way you can move an item at 8,000,000 to before 7,000,000 by changing just it to 6,500,000; and
  2. Every now and again reorder the items as a batch job.

The large increments don't eliminate the problem of doing a large reorder but the need to do a big reorder highly unlikely and the batch job is there to reorder them say once every day/week/month as required.

Changing a whole bunch of items at once is just messy and asking for trouble.

John

If you really want to end up with a continuous sequential order, you can do it like this:

First of all, multiply the sortorder by say 1000

UPDATE testtable SET sortorder = sortorder * 1000

Now do your inserts and insert suitable sortorder values to have the new entries in the right place.

Now do a table update and update the values using the ROW_NUMBER function

UPDATE testtable
SET sortorder = subq.newsortorder
FROM
  (
  SELECT
    ID as innerID,
    ROW_NUMBER() OVER(ORDER BY sortorder ASC) as newsortorder
  FROM testtable
  ) subq
WHERE subq.innerID = ID

The ID is selected as innerID as the updated table can't be aliased and the ID column would otherwise end up ambiguous.

This is updating the sortorder with the row's number when sorted by sortorder.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!