0

需要一个逻辑来为具有父子映射的项目生成序列号。

下面是四个级别的示例项目映射(实际系统有 20 多个级别)。 在此处输入图像描述 生成的映射应该是

100- 1
102- 2
104- 3
106 -4
105 -5
109 -6
103- 7
107- 8

示例数据生成脚本

create table #test(Childid int, parentid int, Sno int)

insert into #test (Childid,parentid)
values (100,0),(102,100),(103,100),(104,102),(105,102),(106,104),(107,103),(109,105)

select * from #test
4

2 回答 2

1

我认为如果您不想使用游标,可以尝试递归 CTE

with cte as (
    select
        t.childid, t.parentid,
        cast(t.childid as nvarchar(max)) as pth
    from test as t
    where t.parentid = 0

    union all

    select
        t.childid, c.parentid,
        c.pth + '.' + cast(t.childid as nvarchar(max)) as pth
    from test as t
        inner join cte as c on c.childid = t.parentid
)
select
    t.childid,
    t.parentid,
    row_number() over(order by pth) as sno 
from cte as c
    inner join test as t on t.childid = c.childid
order by pth

sql 小提琴演示

于 2013-08-17T07:24:05.827 回答
0

On SQL Server >= 2008 there is a type, hierarchyid that should be used exactly for this.

The hierarchyid data type is a variable length, system data type. Use hierarchyid to represent position in a hierarchy.

于 2013-08-17T07:07:35.393 回答