Suppose I have a table like:
id | parentId | name
1 NULL A
2 1 B
3 2 C
4 1 E
5 3 E
I am trying to write a scalar function I can call as:
SELECT dbo.GetId('A/B/C/E')
which would produce "5" if we use the above reference table. The function would do the following steps:
- Find the ID of 'A' which is 1
- Find the ID of 'B' whose parent is 'A' (id:1) which would be id:2
- Find the ID of 'C' whose parent is 'B' (id:2) which would be id:3
- Find the ID of 'E' whose parent is 'C' (id:3) which would be id:5
I was trying to do it with a WHILE loop but it was getting very complicated very fast... Just thinking there must be a simple way to do this.
CTE
version is not optimized way to get the hierarchical data. (Refer MSDN Blog)You should do something like as mentioned below. It's tested for 10 millions of records and is 300 times faster than CTE version :)
Here is an example of functional rcte based on your sample data and requirements as I understand them.
Note that if you change the value of your variable the output will adjust. I would make this an inline table valued function.
I think I have it based on @SeanLange's recommendation to use a recursive CTE (above in the comments):