使用CTE在子父关系中缺少父行

时间:2012-02-07 07:28:59

标签: sql-server-2005 parent-child common-table-expression

我有一个临时表,其中我有以下数据,我想用他的父categoryID过滤子行,直到它在这些层次结构中该父级的顶部。

Parent missing in Parent Child relationship

;with cte (rowid,ParentCategoryID,CategoryID,Status,Level,CategoryName,ISProduct) as
(
     Select  rowid,ParentCategoryID,CategoryID,Status,Level,CategoryName,ISProduct from #newtemp      where ParentCategoryId!=0

     union all
     select cte.rowid,cte.ParentCategoryID,cte.CategoryID,cte.Status,cte.Level,cte.CategoryName,cte.ISProduct
     from  #newtemp inner join cte ON cte.CategoryId=#newtemp.ParentCategoryId
)
select * from cte

2 个答案:

答案 0 :(得分:1)

您需要在c.ParentCategoryId = #newtemp.CategoryID

上替换cte.CategoryId =#newtemp.ParentCategoryId
;with cte (rowid,ParentCategoryID,CategoryID,Status,Level,CategoryName,ISProduct) as
 (
  Select  rowid, ParentCategoryID, CategoryID, Status, Level, CategoryName, ISProduct 
  from #newtemp  
  where ParentCategoryId!=0
  union all
  select t.rowid, t.ParentCategoryID, t.CategoryID, t.Status, t.Level, t.CategoryName, t.ISProduct
  from  #newtemp t inner join cte c ON c.ParentCategoryId = t.CategoryID
  )
  select * from cte

SQLFiddle上的演示

答案 1 :(得分:0)

如果我理解你的话。你是这样的:

首先是一些测试数据:

DECLARE @tbl TABLE
            (
                rowid INT,
                parentCategoryID INT,
                CategoryID INT,
                [Status] INT,
                [Level] INT, 
                CategoryName VARCHAR(100),
                ISProduct BIT
            )

INSERT INTO @tbl
SELECT 1,0,1,1,0,'jewellary',1 UNION ALL
SELECT 2,0,2,1,0,'f',0 UNION ALL
SELECT 11,2,4,1,10,'ghdf',1

然后CTE就是这样:

;WITH cte_name (rowid,CategoryID,parentCategoryID,HasChildren)
AS
(
SELECT
    tbl.rowid,
    tbl.CategoryID,
    tbl.parentCategoryID,
    CASE WHEN EXISTS 
            (
                SELECT
                    NULL
                FROM
                    @tbl AS tblInner
                WHERE
                    tblInner.parentCategoryID=tbl.CategoryID
            )
        THEN 1
        ELSE 0
    END
    AS HasChildren
FROM
    @tbl AS tbl
WHERE
    tbl.parentCategoryID=0
UNION ALL
SELECT
    tbl.rowid,
    tbl.CategoryID,
    tbl.parentCategoryID,
    cte.HasChildren
FROM
    @tbl AS tbl
    JOIN cte_name AS cte
        on cte.CategoryID=tbl.parentCategoryID
)

SELECT 
    tbl.*
FROM 
    cte_name
    JOIN @tbl AS tbl
        ON cte_name.rowid=tbl.rowid
WHERE
    cte_name.HasChildren=1