In actual query, we often encounter examples that require recursive query. The version before SQL SERVER 2005 can be implemented by function method, and after SQL SERVER 2005, CTE can be used (Common Table Expression is introduced after SQL SERVER 2005 version). a feature of ) to query.
--Test Data if not object_id(N'T') is null drop table T Go Create table T([id] int,[pid] int,[num] int) Insert T select 1,0,1 union all select 2,1,1 union all select 3,2,1 union all select 4,2,1 union all select 5,2,1 union all select 6,3,1 union all select 7,3,1 Go -- end of test data
We want to accumulate results upwards, calculate how many subsets are at each level, function way, create a new function:
IF OBJECT_ID('dbo.f_GetChildren') IS NOT NULL DROP FUNCTION dbo.f_GetChildren GO CREATE FUNCTION f_GetChildren ( @id INT , @pid INT , @num INT ) RETURNS @tab TABLE ( [id] INT , [pid] INT , [num] INT ) AS BEGIN INSERT @tab SELECT @id , @pid , @on one WHILE @@rowcount > 0 BEGIN INSERT @tab SELECT T.id , T.pid , T.num FROM T JOIN @tab t1 ON T.pid = t1.id WHERE NOT EXISTS ( SELECT * FROM @tab WHERE T.id = [@tab].id ) END RETURN END GO
transfer:
SELECT id , ( SELECT SUM(num) FROM f_GetChildren(id, pid, num) ) AS sumnum FROM T
result:
Ways to use CTE:
;WITH cte AS ( SELECT *,id AS sumid FROM dbo.T UNION ALL SELECT T.*,cte.sumid FROM T JOIN cte ON T.pid=cte.ID ) SELECT sumid,SUM(num) AS sumnum FROM cte GROUP BY sumid
result:
The above are two basic implementations of recursion, function and CTE form.