Skip to content

Instantly share code, notes, and snippets.

@vadimii
Created June 27, 2012 17:11
Show Gist options
  • Save vadimii/3005452 to your computer and use it in GitHub Desktop.
Save vadimii/3005452 to your computer and use it in GitHub Desktop.
Update order of something
declare @ProjectID int, @SectionID int, @NewOrder int
set @ProjectID = 48
set @SectionID = 36
set @NewOrder = 4
;with NewOrder1 as (
select ID, [Order], rank() over (order by [Order]) as n, 1 as m
from ProjectDescriptionSection
where [Order] <= @NewOrder and ProjectID = @ProjectID and ID <> @SectionID
union all
-- .5 - less than last previous row if last previous row has same order
select ID, [Order], @NewOrder - .5 as n, 1 as m
from ProjectDescriptionSection
where ID = @SectionID
union all
select ID, [Order], rank() over (order by [Order]) as n, 2 as m
from ProjectDescriptionSection
where [Order] > @NewOrder and ProjectID = @ProjectID and ID <> @SectionID
), NewOrder2 as (
select ID, [Order], row_number() over (order by m, n) as r from NewOrder1
)
select * from NewOrder2
--update ProjectDescriptionSection
--set [Order] = n.r
--from ProjectDescriptionSection c
--inner join NewOrder2 n on n.ID = c.ID
ID Order r
------- ------- -------
37 1 1
35 3 2
34 4 3
36 2 4
33 5 5
424 6 6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment