I use the code below to gather data to populate a tree control in my software. Each company can have an 'owned by' reference added which helps me link one to another. If someone selects the wrong 'owned by' company and chooses one already listed then I get an error with the following message The maximum recursion 100 has been exhausted before statement completion which is fine. I am trying to stop this message without having to save the offending record and run the code below, then reverse the save by removing the incorrect 'owned by' value if the error occurs. I would like to run the code below but add in the values being updated to it and then run it. Is that even possible? any other advice would be gratefully received.
;with PathUp as (
select Company_ID, Owned_Company_ID as Parent_ID, 0 as Level
from Company c
where c.Company_ID = 16336
union all
select c.Company_ID, c.Owned_Company_ID, PathUp.Level - 1 as Level
from Company c join PathUp on c.Company_ID = PathUp.Parent_ID
where c.Company_ID > 0 and c.Company_id <> c.Owned_Company_ID
)
select * from PathUp
Simple data sample
Co Owner
1 2
2 3
3 4
4 1
So record 4 cannot own record 1 as it would be a loop. I want to test row 4 before saving it to the record.