答案 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