Skip to content
Advertisement

Returning all components multiple levels under a parent component

I have a hierarchical database out of which I would like to return all components in an asset with a specific common parent component.

Components in table astComponents are linked to their parent components with a ParentComponentId referring to the Id of other components. This, however, only shows the parent one level up.

Additionally, all components are linked to an asset by an AssetId key, linking to the Id key in table astAssets.

I am able to make a simple query (below) to retrieve all components from a specific asset. I can’t figure out how to return all components from a specific asset sharing the same parent component. This parent component may (relative to a child component) 1 to multiple levels up.

The above query returns components and their parents one level up. Were I to specify the parent code, it would only return the child components one level below this specified component, instead of all levels down.

Advertisement

Answer

Okay, without any data to work with there’s a lot of guesswork going on here. I created some data:

What you can do with this is to use recursion to map out all the components that share a common parent, and record which asset they belong to, e.g.:

I bet your tables don’t work like this, so you would need to tweak this to suit. In my case I get the following results:

So I can see that components #1 and #5 have no parents, so these are “top level” components, and I can also see which components link to which assets.

Now it’s simply a case of replacing the SELECT * FROM cte part of my query with something like this:

Gives me all the components that share a parent where the parent has an asset code of 201810000:

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement