with Test_Recursion(Id,ParentId)
AS
(
select Id,ParentId from [V_KPI_DetailsActivities] where ParentId = 4 --没有引用CTE自身必须放在第一个递归行之上
union all --没有引用CTE自身的语句和第一个递归行之间必须用UNION ALL
select a.Id,a.ParentId from [V_KPI_DetailsActivities] as a join Test_Recursion as b on a.parentid=b.id--递归行
)
select Id into #temp from Test_Recursion;
select row_number() over (order by id ) as rowid,* from [V_KPI_DetailsActivities] where ProjectId=13
and ID = 4 or ID in (select Id from #temp )
drop table #temp;