Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You are being catched in a loop because first you select this row:</p> <pre><code>2 1 2 '2012-01-22' </code></pre> <p>then </p> <pre><code>2 2 3 '2012-01-10' </code></pre> <p>then </p> <pre><code>2 3 1 '2012-01-05' </code></pre> <p>and then first line again and again. You need to check is your data consistent enough for your report or not.</p> <p>Or, maybe you need to add following condition to your CTE:</p> <pre><code>ct.previous_status_id &gt; sc.previous_status_id </code></pre> <p>Or, you can change your script by addind parameter that is controling the level of recursion like that:</p> <pre><code>with change_tree as ( SELECT sc.order_id, sc.previous_status_id, sc.next_status_id, cast(sc.next_status_id as varchar(max)) as status_path, sc.Create_Date as StartDate, sc.Create_Date as EndDate, 1 AS deep FROM status_change sc WHERE previous_status_id = 1 AND order_id = 2 UNION ALL SELECT sc.order_id, sc.previous_status_id, sc.next_status_id, ct.status_path + ',' + cast(sc.next_status_id as varchar(max)) sc.Create_Date as StartDate, st.Create_Date as EndDate, ct.deep + 1 AS deep FROM status_change sc JOIN change_tree ct ON ct.next_status_id = sc.previous_status_id AND ct.order_id = sc.order_id WHERE deep &lt; 3 ) SELECT * FROM change_tree WHERE status_path = '1,2,3'; </code></pre> <p>Or, change your script in this way (this will restrict your recursion from going in wrong ways):</p> <pre><code>with change_tree as ( SELECT sc.order_id, sc.previous_status_id, sc.next_status_id, cast(sc.next_status_id as varchar(max)) as status_path, sc.Create_Date as StartDate, sc.Create_Date as EndDate FROM status_change sc WHERE previous_status_id = 1 AND order_id = 2 UNION ALL SELECT sc.order_id, sc.previous_status_id, sc.next_status_id, ct.status_path + ',' + cast(sc.next_status_id as varchar(max)) sc.Create_Date as StartDate, st.Create_Date as EndDate FROM status_change sc JOIN change_tree ct ON ct.next_status_id = sc.previous_status_id AND ct.order_id = sc.order_id WHERE '1,2,3' LIKE ct.status_path + ',' + cast(sc.next_status_id as varchar(max)) + '%' ) SELECT * FROM change_tree WHERE status_path = '1,2,3'; </code></pre>
    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.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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