如何查找其父类型为Family的Item类型的所有对象

时间:2019-03-21 12:10:06

标签: sql-server

这是我的对象表-

enter image description here

我正在尝试编写一个查询,该查询可以使用其父类型A来获取所有类型C的对象。因此查询应返回

enter image description here

我正在尝试使用递归来执行此操作,但未获得所需的结果。任何帮助,将不胜感激。谢谢。

2 个答案:

答案 0 :(得分:1)

这可以为您提供帮助,但是如果逻辑符合您的要求是另一个问题:

DECLARE @ObjectID int = 3;
DECLARE @EndType char(1) = 'A';

WITH VTE AS(
    SELECT *
    FROM (VALUES(1,'A',NULL),
                (2,'B',1),
                (3,'C',2))V(ObjectID, ObjectType, ParentID)),
rCTE AS(
    SELECT V.ObjectID,
           V.ObjectType,
           V.ParentID,
           V.ObjectID AS StartID, 
           V.ObjectType AS StartType 
    FROM VTE V
    WHERE v.ObjectID = @ObjectID
    UNION ALL
    SELECT V.ObjectID,
           V.ObjectType,
           V.ParentID,
           r.StartID,
           r.StartType
    FROM rCTE r
         JOIN VTE V ON V.ObjectID = r.ParentID)
SELECT r.StartID AS ObjectID,
       r.StartType AS ObjectType,
       r.ObjectID AS ParentObjectID,
       r.ObjectType AS PArentObjectType
FROM rCTe r
WHERE r.ObjectType = @EndType;

答案 1 :(得分:0)

样本数据

DECLARE @Temp AS TABLE (ObjectId INT,ObjectType VARCHAR(2),ParentObjectId INT)
INSERT INTO @Temp
SELECT 1,'A',NUll UNION ALL
SELECT 2,'B',1 UNION ALL
SELECT 3,'C',NULL UNION ALL
SELECT 4,'D',3 UNION ALL
SELECT 5,'E',4 UNION ALL
SELECT 6,'B',3 

Sql服务器脚本

;WITH CTE
AS
(
SELECT ObjectId,
       ObjectType,
       ParentObjectId,
       CAST('\'+ CAST(ObjectId AS VARCHAR(MAX))AS VARCHAR(MAX)) AS [ObjectIdHierarchy] ,
       CAST('\'+ ObjectType AS VARCHAR(MAX)) AS [Hierarchy] 
FROM @Temp
WHERE ParentObjectId IS NULL
UNION ALL
SELECT t.ObjectId,
       t.ObjectType,
       t.ParentObjectId,
       [ObjectIdHierarchy]+'\'+ CAST(t.ObjectId AS VARCHAR(MAX)) AS [ObjectIdHierarchy],
       [Hierarchy]+'\'+ t.ObjectType  AS [Hierarchy]

FROM CTE c
INNER JOIN @Temp t
ON t.ParentObjectId = c.ObjectId
)
SELECT ObjectId,
       ObjectType, 
   LEFT(RIGHT([ObjectIdHierarchy],LEN([ObjectIdHierarchy])-1),1) AS ParentObjectId,
   LEFT(RIGHT([Hierarchy],LEN([Hierarchy])-1),1) AS ParentChildHierarchy 
FROM CTE
WHERE ObjectId =1 

结果

ObjectId    ObjectType  ParentObjectId  ParentChildHierarchy
------------------------------------------------------------
1               A           1                   A