It is normal in databases to have hierarchical tables, that is, tables that are related with themselves, forming a parent-child relation. For example, consider this:
The parent_id column points to the parent record, which, in some cases, will not exist.
So, imagine we have a number of records, such as:
How can we find the id of the topmost parent? In this case, it will always be 1, of course.
In SQL Server, we have two options:
Let’s see how to implement each.
We need to write a CTE that starts with some record and goes all the way up until it finds the parent. Let’s wrap it in a nice scalar function:
I won’t explain here how CTEs work, they have been around for quite some time, and there are several posts how there for that.
The other approach is using a recursive function. The gotcha here is that when we create a function, it is compiled, and if it has a reference to itself – which doesn’t exist first – it will fail. Therefore, we need to first create a dummy function and then change it to do what we want:
You can get results from the two functions by running the following T-SQL queries:
Interesting, both execution plans are exactly the same:
I can’t really recommend one over the other, since from my tests, both took the same amount of time (you will need far more records than the ones from my sample to tell that).
So, any thoughts from database gurus out there?