平面表中的SQL父子临时表

时间:2019-06-27 16:14:45

标签: sql-server-2012

我想知道是否有人可以帮助我完成CTE。 如何将这些数据转换为n个级别的父级,子级,孙子级?我在表值函数中尝试了递归CTE,但未以我想要的格式带回数据。我需要一个ID,ParentID。似乎我需要将这些数据分解为2个临时表,并使用merge,output子句引起ID,ParentID关系? 有人可以建议

      WITH Hierarchy 
    AS
    (
  SELECT 0 as level ,*
      FROM [SignerRelationship] 
      WHERE [ParentId] = 795
      UNION ALL
 SELECT Hierarchy.level + 1 as level ,[SignerRelationship].*
      FROM [SignerRelationship]  JOIN
      Hierarchy  ON [SignerRelationship].[ParentId] = Hierarchy.[ChildId]

    )
      SELECT * from Hierarchy 

这就是我要实现的目标

enter image description here

CREATE TABLE [dbo].[SignerRelationship](
        [SignerRelationshipId] [int] IDENTITY(1,1) NOT NULL,
        [ParentId] [int] NOT NULL,
        [ParentRelationshipTypeId] [int] NOT NULL,
        [ChildId] [int] NOT NULL,
        [ChildRelationshipTypeId] [int] NOT NULL,
     CONSTRAINT [SignerRelationshipPK] PRIMARY KEY CLUSTERED 
    (
        [SignerRelationshipId] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY]

    GO


SignerRelationshipId,ParentId,ParentRelationshipTypeId,ChildId,ChildRelationshipTypeId
    1,795,1000,525,1001
    3,795,1000,28416,1001
    4,795,1000,35398,1001
    5,795,1000,6000770,1001
    6,795,1000,6001052,1001
    7,795,1000,6000771,1001
    8,28416,1001,6000498,1001
    9,35398,1001,35458,1001
    11,35398,1001,35458,1
    12,35398,1000,4836632,1

非常感谢您。

0 个答案:

没有答案