I have the following recursive table-valued function in MS SQL, in order to retrieve a hierarchy of objects from the database:
WITH tmpField (ParentNum, ChildNum, FieldNum, FieldDescr, Iteration) AS
(
SELECT Field.ParentNum, Field.ChildNum, Field.FieldNum, Field.FieldDescr, 1
FROM Field
WHERE Field.ParentNum = @ParentNum
UNION ALL
SELECT Field.ParentNum, Field.ChildNum, Field.FieldNum, Field.FieldDescr, tmpField.Iteration + 1
FROM Field INNER JOIN
tmpField on Field.ParentNum = tmpField.ChildNum
)
SELECT DISTINCT ParentNum AS ParentNum, ChildNum AS ChildNum, FieldNum, FieldDescr
FROM tmpField
I want to modify it in the following way:
In the last iteration, when there are no more 'children', I want the ChildNum
field to have the value of FieldNum
. In all previous iterations, ChildNum
should have the value of the ChildNum
field, as it is now.
Can anyone suggest a method to achieve this, using the above query as a starting point?
Please note: despite its name, the field ChildNum
does not reference any children of a row, but it should be interpreted as the identifier of that row.