问题
I have the following datasets in SQL Server
Hierarchy Table:
Report | Immediate Parent
Child1 Parent1
Child2 Parent1
Child3 Parent2
Parent1 Grandparent1
Parent2 Grandparent1
Data Table (Only exists for Base level children):
Report | Sales
Child1 1000
Child2 1000
Child3 1000
From this I need to create a dataset which contains
Report | Sales
Parent1 2000
Parent2 1000
Grandparent1 3000
I do not know how many hierarchy levels there will be, could be great *10 grandparents. My solution to this problem was to use recursion and dynamic SQL to keep creating temporary tables for each hierarchy level i.e.
Create a temp table for parents, join data table to hierarchy table and sum(sales)
Create temp table for grandparents, join parent temp table to hierarchy table and sum(sales)
Rinse and repeat until no rows affected (@@rowcount)
Merge all temp tables into permanent table
However from reading the forums I understand that:
- Recursion is to be avoided,
- Dynamic SQL is to be avoided,
- @@Rowcount is to be avoided
My question is, how to approach the problem without using all this bad practice?
来源:https://stackoverflow.com/questions/35362529/working-with-a-dynamic-hierarchy-sql-server