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.