I use nested sets (the so-called modified pre-order tree traversal) to save the list of groups, and I'm trying to find a quick way to create breadcrumbs (as rows, not tables) for ALL groups once. My data is also stored using the adjacency list model (there are triggers for synchronizing the two).
So for example:
ID Name ParentId Left Right 0 Node A 0 1 12 1 Node B 0 2 5 2 Node C 1 3 4 3 Node D 0 6 11 4 Node E 3 7 8 5 Node F 4 9 9
What the tree represents:
I would like to have a custom function that returns a table:
ID Breadcrumb 0 Node A 1 Node A > Node B 2 Node A > Node B > Node C 3 Node A > Node D 4 Node A > Node D > Node E 5 Node A > Node D > Node F
To make this a little more complicated (although this goes beyond the scope of the question), I also have user restrictions that must be followed. So, for example, if I only have access to id = 3, when I run the request, I should get:
ID Breadcrumb 3 Node D 4 Node D > Node E 5 Node D > Node F
I have a user-defined function that takes a user id as a parameter and returns a table with the identifiers of all valid groups, so until somewhere in the query
WHERE group.id IN (SELECT id FROM dbo.getUserGroups(@userid))
he will work.
I have an existing scalar function that can do this, but it just doesn't work with any reasonable number of groups (takes> 10 seconds on 2000 groups). It takes the groupid and userid parameters as the parameter and returns nvarchar. It finds the data of the parent group (1 query to grab the values ββleft / right, another to search for parents), restricts the list to groups the user has access to (using the same WHERE clause as above, so another query) , and then uses the cursor to step through each group and adds it to the line before finally returning this value.
I need a way for this to work quickly (e.g.. <= 1s), on the fly.
This is on SQL Server 2005.