Note that there are some explanatory texts on larger screens.

plurals
  1. POCommon table expressions, how to avoid infinite recusion when traversing a graph?
    primarykey
    data
    text
    <p>I have a simple weighted graph</p> <pre><code> A 1 / \\ 0.5 / \\0.5 B C </code></pre> <p>Suppose this describes a family and A is the father, B is the son and C is the mother. Let's say B is studying in an university and A has bought an apartment for him. A is living with C in a house which is commonly owned, 50-50.</p> <p>I want to transform the graph into a tree, starting from A: ie. </p> <ul> <li>A owns 50% of the place C is living in</li> <li>A owns 100% of the place B is living in</li> <li>C owns 50% of the place A is living in</li> </ul> <p>The graph and the generated tree could be more elaborate but I hope you get the more general picture.</p> <p>On SQL Server 2005 I have</p> <pre><code>Drop Table #graph; Create Table #graph (FirstVertex VarChar(1) Not Null, SecondVertex VarChar(1) Not Null, Weight float); Insert #graph Values('A','B',1); Insert #graph Values('A','C',0.5); Insert #graph Values('C','A',0.5); </code></pre> <p>and I'm using the following common table expression to traverse the graph, starting from 'A':</p> <pre><code>With GraphRecursion (FirstVertex, SecondVertex, Weight, Level) As ( Select FirstVertex, SecondVertex, Weight, 0 As Level From #graph Where FirstVertex='A' Union all Select a.FirstVertex, a.SecondVertex, a.Weight, b.Level+1 From #graph a Inner Join GraphRecursion b On a.FirstVertex=b.SecondVertex --And b.Level&lt;=1 ) Select * From GraphRecursion; </code></pre> <p>This causes</p> <pre><code>Msg 530, Level 16, State 1, Line 11 The statement terminated. The maximum recursion 100 has been exhausted before statement completion. </code></pre> <p>Limiting the level of recursion by uncommenting the <code>And b.Level&lt;=1</code> gives the expected results, but that's obviously not very useful for any practical use.</p> <p>Is there a way to reference the previous iterations so that in the above example edges (ie. the FirstVertex, SecondVertex pairs) would not be repeated?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload