SQL 服务器查询以根据用户提供的 id 获取嵌套的子记录

SQL Server query to get nested child records based on id provided by user

我有 SQL 以下格式的服务器数据:

在上面table中,parentid和sourceid是相关的,就像父子关系。

第一行的parentid 'A'是第二行的sourceid。用户将提供 sourceid 的输入,根据该 sourceid,我需要获取其相关的子记录。

例如,如果用户提供的输入源id为'A1',则输出应如下所示:

我尝试使用自连接,但无法在 table 中获取相关的子记录。

select * 
from testrecords1 t1
join testrecords1 t2 on t1.parentid = t2.sourceid
where t1.sourceid = 'A1'

该查询结果只有一条记录。请提供更正/建议以实现所需的输出。

递归查询可以使用Common Table Expression (CTE)

查询可以写成:

;with MyCTE 
as
   (  
      SELECT Parentid, Sourceid from testrecords1 where SourceId = @SourceId
        UNION ALL  
      SELECT t1.Parentid, t1.Sourceid from testrecords1 t1
      inner join MyCTE t2 on t1.SourceId = t2.Parentid
    )  
 
SELECT * FROM MyCTE 

其中 @SourceId 是过滤器的参数。