Если я правильно вас понял.Вы что-то вроде этого:
Сначала некоторые тестовые данные:
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