CREATE TABLE tb(ID int PRIMARY KEY,PID int,Num int)
INSERT tb SELECT 1,NULL,100
UNION ALL SELECT 2,1 ,200
UNION ALL SELECT 3,2 ,300
UNION ALL SELECT 4,3 ,400
UNION ALL SELECT 5,1 ,500
UNION ALL SELECT 6,NULL,600
UNION ALL SELECT 7,NULL,700
UNION ALL SELECT 8,7 ,800
UNION ALL SELECT 9,7 ,900
GO
--计算的存储过程
CREATE PROC p_Calc
AS
SET NOCOUNT ON
DECLARE @Level int
SET @Level=1
SELECT ID,PID,SUM_Num=Num,
Level=CASE
WHEN EXISTS(SELECT * FROM tb WHERE PID=a.ID)
THEN 0 ELSE 1 END
INTO # FROM tb a
WHILE @@ROWCOUNT>0
BEGIN
SET @Level=@Level+1
UPDATE a SET
Level=@Level,
SUM_Num=ISNULL(a.SUM_Num,0)+ISNULL(b.SUM_Num,0)
FROM # a,(
SELECT aa.PID,SUM_Num=SUM(aa.SUM_Num)
FROM # aa,(SELECT DISTINCT PID FROM # WHERE Level=@Level-1)bb
WHERE aa.PID=bb.PID
AND NOT EXISTS(
SELECT * FROM # WHERE PID=aa.PID AND Level=0)
GROUP BY aa.PID
)b WHERE a.ID=b.PID
END
SELECT a.*,b.SUM_Num
FROM tb a,# b
WHERE a.ID=b.ID
GO
--调用存储过程进行计算
EXEC p_Calc
/*--结果
ID PID Num SUM_Num
---------------- ------------------ ------------------- --------------------
1 NULL 100 1500
2 1 200 900
3 2 300 700
4 3 400 400
5 1 500 500
6 NULL 600 600
7 NULL 700 2400
8 7 800 800
9 7 900 900
--*/
INSERT tb SELECT 1,NULL,100
UNION ALL SELECT 2,1 ,200
UNION ALL SELECT 3,2 ,300
UNION ALL SELECT 4,3 ,400
UNION ALL SELECT 5,1 ,500
UNION ALL SELECT 6,NULL,600
UNION ALL SELECT 7,NULL,700
UNION ALL SELECT 8,7 ,800
UNION ALL SELECT 9,7 ,900
GO
--计算的存储过程
CREATE PROC p_Calc
AS
SET NOCOUNT ON
DECLARE @Level int
SET @Level=1
SELECT ID,PID,SUM_Num=Num,
Level=CASE
WHEN EXISTS(SELECT * FROM tb WHERE PID=a.ID)
THEN 0 ELSE 1 END
INTO # FROM tb a
WHILE @@ROWCOUNT>0
BEGIN
SET @Level=@Level+1
UPDATE a SET
Level=@Level,
SUM_Num=ISNULL(a.SUM_Num,0)+ISNULL(b.SUM_Num,0)
FROM # a,(
SELECT aa.PID,SUM_Num=SUM(aa.SUM_Num)
FROM # aa,(SELECT DISTINCT PID FROM # WHERE Level=@Level-1)bb
WHERE aa.PID=bb.PID
AND NOT EXISTS(
SELECT * FROM # WHERE PID=aa.PID AND Level=0)
GROUP BY aa.PID
)b WHERE a.ID=b.PID
END
SELECT a.*,b.SUM_Num
FROM tb a,# b
WHERE a.ID=b.ID
GO
--调用存储过程进行计算
EXEC p_Calc
/*--结果
ID PID Num SUM_Num
---------------- ------------------ ------------------- --------------------
1 NULL 100 1500
2 1 200 900
3 2 300 700
4 3 400 400
5 1 500 500
6 NULL 600 600
7 NULL 700 2400
8 7 800 800
9 7 900 900
--*/