7

我有以下问题:我有一个用于维护分层数据的表。我想使用 SQL 2005 中的 CTE。

WITH tree (id, parentid, code, name) AS
(
    SELECT id, ofs.ParentID, ofs.code, ofs.name
      FROM OrganizationFeatures ofs
     WHERE ofs.ParentID IS NULL

    UNION ALL

    SELECT ofs.id, ofs.ParentID, ofs.code, ofs.name
      FROM OrganizationFeatures ofs
      JOIN tree ON tree.ID = ofs.ParentID
)

select * from tree

但我想按代码排序,结果如下:

1
1/1
1/1/1
1/1/2
1/2/1
1/2/2
2
4/1

等等有什么想法吗?

4

2 回答 2

4

要获得连接的值,您需要在 with 中进行。

要进行排序,您需要在最后一个选择中添加排序依据。

WITH tree (id, parentid, code, name) AS
(
    SELECT id, ofs.ParentID, ofs.code, ofs.name
      FROM OrganizationFeatures ofs
     WHERE ofs.ParentID IS NULL

    UNION ALL

    SELECT ofs.id, ofs.ParentID, tree.code+'/'+ofs.code, ofs.name
      FROM OrganizationFeatures ofs
      JOIN tree ON tree.ID = ofs.ParentID
)

select * from tree order by code

此外,如果代码不是 varchar,则必须转换这段代码 ( tree.code+'/'+ofs.code) 中的代码列才能使其工作。

于 2009-01-23T16:00:55.933 回答
2

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

但我不喜欢这种需要强制转换的解决方案。有没有更好的解决方案?

于 2009-01-25T21:04:56.340 回答