#title 끼워넣기 가끔씩.. 다음과 같이 끼워넣기를 하는 경우가 있다. ||제품||순서|| ||T101||1.0|| ||T103||2.0|| ||T104||3.0|| 1.0과 2.0사이에 소수점을 이용하여 끼워넣기 ||제품||순서|| ||T101||1.0|| ||T102||1.5|| <-- insert || ||T103||2.0|| ||T104||3.0|| 아니면 2.0부터 이후부터 모조리 업데이트 ||제품||순서|| ||T101||1.0|| ||T102||2.0|| <-- insert || ||T103||3.0|| <-- update || ||T104||4.0|| <-- update || 뭐.. 이런 경우가 있다. 내가 접한 사람들은 이렇게 하고는 뭔가 찜찜해 했다. 이런거는 Linked-List와 유사하다. winamp에서 재생 목록의 순서를 이리저리 바꾸는 경우다. 데이터가 많지 않다면 업데이트를 하는 방법도 괜찮고, 데이터가 많다면 소수점을 이용하여 끼워넣는 방법도 괜찮다. 하지만, CTE 재귀를 이용하여 Linked List를 구현하는 방법도 있다. {{{ drop table #linked_list create table #linked_list ( row_id int , next_row_id int , value int ) --head, tail 세팅, head와 tail의 row_id는 상수 insert #linked_list values (0,9,0) , (9,9,0) --3 삽입 begin tran insert #linked_list values (1,9,3); update #linked_list set next_row_id = 1 where row_id = 0; commit; --2 삽입 begin tran insert #linked_list values (2,9,4); update #linked_list set next_row_id = 2 where row_id = 1; commit; --조회 with cte as ( select row_id, next_row_id, value, 1 order_val from #linked_list where row_id = 0 union all select a.row_id, a.next_row_id, a.value, b.order_val + 1 from #linked_list a inner join cte b on a.row_id = b.next_row_id where b.row_id < 9 ) select * from cte order by order_val /* row_id next_row_id value order_val ----------- ----------- ----------- ----------- 0 1 0 1 1 2 3 2 2 9 4 3 9 9 0 4 */ }}}