Skip to content
Advertisement

Combining a recursive CTE with another query

I have a table of locations each of which can have a parent location

I managed to create a recursive CTE which gives me parent location id (plus the original location id) for any given location id

e.g. where LocationId = 3 would return:

In another table I have a query which will return LocationId as one of the fields:

Which with a where clause would return something like:

I’m trying to combine these queries to get the result:

I’m trying the following but it’s still only returning the first row:

Is it possible to merge a recursive query with a normal query like this?

Advertisement

Answer

I guess you have a small bug in your cte. I would suggest to change the query as follows:

With this you receive a list with the value you filter on in the first column and all depending “levels” above this in the second column. This can then be used in order to join to your second table.

Keep in mind that – depending on your number of levels – you will have to take care of MAX RECUSRSION.

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