Loki,我有类似的查询,但它没有按我想要的名称排序,而是按代码排序 - 这是星期五,我超载了。
无论如何,运行您的查询给了我一个错误,有必要强制转换;我不得不按照以下方式更改它:
WITH tree (id, parentid, name, code) AS
(
SELECT id, ofs.ParentID, ofs.name, CAST(ofs.name as varchar(255))
FROM OrganizationFeatures ofs
WHERE ofs.ParentID IS NULL
UNION ALL
SELECT ofs.id, ofs.ParentID, ofs.name, CAST(tree.code+'/'+ofs.name as varchar(255))
FROM OrganizationFeatures ofs
JOIN tree ON tree.ID = ofs.ParentID
)
select * from tree order by code
问题是尽管名称是 varchar,但仍需要强制转换为 varchar。很可能 varchar(255) 不足以处理大树。
所以我做了一个版本,上面提到的问题不是那么大:
WITH tree (id, parentid, name, code) AS
(
SELECT id, ofs.ParentID, ofs.name,
CAST(ROW_NUMBER() OVER (ORDER BY ofs.name ASC) as varchar(255))
FROM OrganizationFeatures ofs
WHERE ofs.ParentID IS NULL
UNION ALL
SELECT ofs.id, ofs.ParentID, ofs.name,
CAST(tree.code +'/' + CAST(ROW_NUMBER() OVER (ORDER BY ofs.name ASC) as varchar(255)) as varchar(255))
FROM OrganizationFeatures ofs
JOIN tree ON tree.ID = ofs.ParentID
)
select * from tree order by code
但我不喜欢这种需要强制转换的解决方案。有没有更好的解决方案?