Working with a dynamic hierarchy SQL Server

杀马特。学长 韩版系。学妹 提交于 2019-12-10 10:21:00

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!