With a table of the following structure and sample data:
TableActivity
-------------
Type VARCHAR(8)
Activity VARCHAR(8)
RelatedActivity VARCHAR(8)
Type Activity RelatedActivity
------------------------------------------
Start a -
Transfer a b
Start b -
Transfer b c
Start c -
Stop c -
Transfer c b
Stop b -
Transfer b a
Stop a -
Would it be possible to write a CTE query to accomplish the following:
GetActivities('a')
Order Activities
-------------------
0 a
1 b
2 c
I'm having a tough time writing one that stops returning rows in the recursive statement.
Any ideas?
Edit
To clarify GetActivities('a'). This function should find the 'Start' activity of 'a' and proceed to find any 'Transfer' activities on 'a'. At that the point the function can then recurse with 'b' and consequently 'c' with the sample data. The query should return all activities related to 'a' via 'Transfers'. This nesting of activities can go as deep as need be and is unknown (so no unions). The difficulty I'm having is that there is another 'Transfer' back down e.g. 'b' -> 'a'. You can see how this would create a loop in the recursive query.
One more clarification: the transfers in the activity table behave as a stack. Here is how the data is populated in the table (in C#):
using (Activity.Start("a"))
{
// transfer to 'b' under covers
using (Activity.Start("b"))
{
// transfer to 'c' under covers
using (Activity.Start("c"))
{
}
// transfer to 'b' under covers
}
// transfer to 'a' under covers
}