使用一个物理表中的公用表表达式在类别下排序子类别

时间:2015-10-09 17:54:31

标签: sql-server common-table-expression recursive-query

我有一个这样的简单表:

CREATE TABLE [dbo].[ProductCategories](
    [ProductCategoryId] [int] IDENTITY(1,1) NOT NULL,
    [ProductCategoryParentId] [int] NULL,
    [ProductCategoryName] [varchar](500) NULL
)

我尝试以递归方式从中选择数据但是按照这样的方式排序数据:

CTE Ordering

我有这个常见的表格表达式我使用:

WITH Categories AS
(
    SELECT Cat.ProductCategoryId
        ,Cat.ProductCategoryName
        ,Cat.ProductCategoryParentId
        ,CAST('Root' AS VARCHAR(500)) AS 'ParentCategory'
        ,0 AS 'Level'
    FROM ProductCategories Cat
    WHERE Cat.ProductCategoryParentId = 0

    UNION ALL

    SELECT Cat.ProductCategoryId
        ,Cat.ProductCategoryName
        ,Cat.ProductCategoryParentId
        ,c2.ProductCategoryName AS 'ParentCategory'
        ,LEVEL + 1
    FROM ProductCategories CAT
    INNER JOIN Categories c2 ON cat.ProductCategoryParentId = c2.ProductCategoryId
    WHERE c2.ProductCategoryId != 0
)
SELECT DISTINCT * FROM Categories
ORDER BY level
,ProductCategoryParentId
,ProductCategoryName

这对于递归我的表并返回不同的级别非常有用,但是我希望将结果与父类别下的子类别一起直接从sql中排序,这样我就不必进行任何重新排序的代码侧的。

我无法绕过这个。

有什么建议吗?

TIA

0 个答案:

没有答案