基于@onaiggac 的变体(您可以使用他的数据:-))
;WITH CTE (id, id_parent, name_product, LEVEL, SORTKEY) AS
(
SELECT id, id_parent, name_product, 1,
CAST(ROW_NUMBER() OVER (ORDER BY name_product) AS VARBINARY(MAX))
FROM @tab where id_parent is null -- Starts with the first level
UNION ALL
SELECT t.id, t.id_parent, t.name_product, C.LEVEL + 1,
C.SORTKEY + CAST(ROW_NUMBER() OVER (ORDER BY t.name_product) AS VARBINARY(MAX))
FROM @tab t
INNER JOIN CTE C ON t.id_parent = C.id
)
SELECT id, id_parent, REPLICATE(' ', LEVEL - 1) + name_product, LEVEL, SORTKEY FROM CTE ORDER BY SORTKEY
这里的诀窍是使用
ROW_NUMBER() OVER (ORDER BY name_product)
进行“内部”排序。就像在@onaiggac 中一样,然后将其组合成二进制文件varbinary(max)
CAST(ROW_NUMBER() OVER (ORDER BY name_product) AS VARBINARY(MAX))
然后递归添加...
C.SORTKEY + CAST(ROW_NUMBER() OVER (ORDER BY t.name_product) AS VARBINARY(MAX))
请注意,这ROW_NUMBER()
将返回一个bigint
... 您可以在将其转换为int
之前将其转换为VARBINARY(MAX)
,例如
CAST(CAST(ROW_NUMBER() OVER (ORDER BY name_product) AS INT) AS VARBINARY(MAX))
如果你真的想要......我认为除非你的树真的很深,否则没有必要。