递归CTE查询 - 我想将@Id作为resultSet的一部分返回

时间:2014-02-10 17:30:06

标签: sql

DECLARE @Id INT
SELECT @Id = 71495
;WITH cte_parents (ParentId)
AS
(    SELECT ParentId  From dbo.TableOne WHERE ChildId =@Id  
UNION ALL
SELECT cp.parentId FROM dbo.TableOne cp
INNER JOIN  cte_parents 
ON cp.ChildId=cte_parents.ParentId  -- Recursive member (RM) is referencing cte_name.
 )

SELECT * FROM cte_parents 


 This Query finds out all the parents for a given value. I have a table with two columns 

 TableOne

 ParentId ChildId

问题是我想将@Id作为resultSet的一部分返回。换句话说,即使没有父亲也应该返回@Id。如果有一个父级,那么它应该返回两个值。一个是传递参数i-e @Id,另一个是父

1 个答案:

答案 0 :(得分:1)

嗯,你可以这样做:

WITH cte_parents (ParentId) AS
      (SELECT ParentId  From dbo.TableOne WHERE ChildId =@Id  
       UNION ALL
       SELECT cp.parentId
       FROM dbo.TableOne cp INNER JOIN 
            cte_parents 
            ON cp.ChildId=cte_parents.ParentId  -- Recursive member (RM) is referencing cte_name.
      )
SELECT *
FROM cte_parents 
union all
SELECT @id;

这只会在最终的select子句中添加额外的行。