1

假设我的表中有以下数据,其中 anItem的父 ID 为 0。但父级只能有三个子级别/子级。也就是说,我们需要每个 item 的 parentId = 0,并且每个 parent 最多可以有三个级别的孩子。

pkProductID       Name            ParentId 
-------------------------------------------
1                 Cloth              0
2                 T-Shirts           1
3                 Men-Shirts         2
4                 Women-Shirts       2
5                 Kids-Shirts        3
6                 Cosmetics          0
7                 Creams             6
8                 Men-cream          7
9                 Women-Cream        7
10                Kids-cream         9

我们需要包含具有parentID=0然后 2 个级别的子项的列表,这意味着从上面我只需要这些项:

1 Cloth
2 T-Shirts
3 Men-Shirts
4 Women-Shirts
6 Cosmetics
7 Creams
8 Men-Cream
9 Women-Cream
4

2 回答 2

2

以下代码应该可以完成工作(相应地更改tablecolumns命名):

use [DemoDB]
GO
WITH Emp_CTE AS (
SELECT ProductId, Name, ParentID, 0 as [Level]
FROM [dbo].[Products]
WHERE ParentId = 0
UNION ALL
SELECT p.ProductId, p.Name, p.ParentID, [Level] + 1
FROM [dbo].[Products] as p
INNER JOIN Emp_CTE ecte ON ecte.ProductId = p.ParentID
WHERE [Level] < 2
),
CTE2 AS
(
    SELECT [dbo].[Products].*
    FROM Emp_CTE
        INNER JOIN [dbo].[Products] ON Emp_CTE.ProductId = [dbo].[Products].ParentID
)
SELECT * FROM CTE2

GO
于 2013-04-13T08:40:15.613 回答
1

您可以将递归 CTE 用于此类任务,请查看此处显示一个简单示例的链接:http: //blog.sqlauthority.com/2008/07/28/sql-server-simple-example-of -recursive-cte/这里还有另一个例子http://msdn.microsoft.com/en-us/library/ms186243%28v=sql.105%29.aspx

CREATE TABLE #clothes(
pkProductID INT,
NAME VARCHAR(50),
ParentId INT
)


INSERT  INTO #clothes
        ( pkProductID, NAME, ParentId )
VALUES  ( 1, 'cloth', 0 )

INSERT  INTO #clothes
        ( pkProductID, NAME, ParentId )
VALUES  ( 2, 'tshirt', 1 )

INSERT  INTO #clothes
        ( pkProductID, NAME, ParentId )
VALUES  ( 3, 'mens tshirt', 2 )

INSERT  INTO #clothes
        ( pkProductID, NAME, ParentId )
VALUES  ( 4, 'womens tshirt', 2 )

INSERT  INTO #clothes
        ( pkProductID, NAME, ParentId )
VALUES  ( 5, 'kids tshirt', 3 )

INSERT  INTO #clothes
        ( pkProductID, NAME, ParentId )
VALUES  ( 6, 'cosme', 0 )

INSERT  INTO #clothes
        ( pkProductID, NAME, ParentId )
VALUES  ( 7, 'cream', 6 )

INSERT  INTO #clothes
        ( pkProductID, NAME, ParentId )
VALUES  ( 8, 'm cream', 7 )

INSERT  INTO #clothes
        ( pkProductID, NAME, ParentId )
VALUES  ( 9, 'w cream', 7 )

INSERT  INTO #clothes
        ( pkProductID, NAME, ParentId )
VALUES  ( 10, 'kids cream', 9 )

WITH myCTE AS (
SELECT pkProductID ,
        NAME ,
        ParentId, 0 AS ItemLevel FROM #clothes
        WHERE ParentId = 0

UNION all
SELECT c.pkProductID ,
        c.NAME ,
        c.ParentId, ItemLevel + 1 FROM #clothes c INNER JOIN myCTE mc ON mc.pkProductID = c.ParentId
)
SELECT * FROM   myCTE WHERE ItemLevel <=2 ORDER BY pkProductID
于 2013-04-13T08:24:29.837 回答