0

我有一个带有父子层次结构的表。

Id  ParentId
-----------------------------------
1   1  -- root node
2   1  -- 1st level child
3   1  -- 1st level child
4   2  -- 2nd level child (there can be any number of child levels)
5   5  -- root node
6   5  -- 1st level child

我想在此表中添加一个新列,名为sortindex. 父节点下的每一级子节点都应该有自己的排序索引。例如,第一级子节点将拥有自己的sortindex.

id   parentid   sortindex
-------------------------
2       1          1
3       1          2

同样,根节点将有自己的一组sortindex等。

具有排序索引的表应如下所示:

Id  ParentId SortIndex
----------------------
1   1         1
2   1         1
3   1         2
4   2         1
5   5         2
6   5         1

现在,我刚刚添加了sortindex默认值为 0 的列,但我想使用存储过程来更新每条记录的sortindex. 所以它应该计算每条记录sortindex并更新它。

如何做到这一点?谢谢!

4

1 回答 1

0

这有用吗。?

Create table #tab1(id int, parentId int)

insert into #tab1
SELECT 1,1  Union All
SELECT 2,1  Union All
SELECT 3,1  Union All
SELECT 4,2  Union All
SELECT 5,5  Union All
SELECT 6,5 


ALTER TABLE #tab1
ADD sortindex int


;with cte
AS
(
    SELECT id,ParentId,ROW_NUMBER() OVER(order by id)sortindex from #tab1 where id=ParentId
    Union ALL
    Select id,ParentId ,ROW_NUMBER() OVER(Partition by Parentid order by id)   from #tab1 where id!=ParentId

)

UPDATE t
SET t.sortindex=cte.sortindex
FROM #tab1 t
JOIN cte ON t.id=cte.id 

Select * from #tab1

Drop table #tab1
于 2018-05-31T05:34:32.343 回答