How to get result from parent child table

前端 未结 4 1075
一个人的身影
一个人的身影 2021-01-22 14:44

Work on SQL-Server. My table structure is below

CREATE TABLE [dbo].[AgentInfo](
    [AgentID] [int] NOT NULL,
    [ParentID] [int] NULL,
 CONST         


        
4条回答
  •  孤城傲影
    2021-01-22 15:12

    You can try this, to get a tree of the elements:

    WITH CTE_AgentInfo(AgentID, ParentID, BaseAgent)
    AS(
      SELECT 
        AgentID,
        ParentID,
        AgentID AS BaseAgent
       FROM AgentInfo
       WHERE ParentID = -1
      UNION ALL
         SELECT 
        a.AgentID,
        a.ParentID,
        a.AgentID AS BaseAgent
       FROM AgentInfo a
       INNER JOIN CTE_AgentInfo c ON
        c.AgentID = a.ParentID
      )
    SELECT * FROM CTE_AgentInfo
    

    And here is an SQLFiddle demo to see it.

提交回复
热议问题