變基於@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))
被然後遞歸additioned組成...
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))
,如果你真的想之前......我不認爲這是necess ary除非你的樹是真的深。
我們怎樣才能在沒有看到代碼的情況下提供幫助 – Bort 2012-08-16 00:56:52
數據庫軟件及其版本的選擇對可能的解決方案有相當大的影響。 What'cha runnin'? – HABO 2012-08-16 01:24:01
[CTE的真實遞歸?]的可能的重複?(http://stackoverflow.com/questions/11636420/a-real-recursion-with-cte) – 2012-08-16 04:24:46