Related question: TSQL check if specific rows sequence exists
I'm asking second question about recursion, because this time it is different thing (in my opinion) so please don't delete it.
I have table containing values:
ORDER_ID Previous_STATUS_ID Next_STATUS_ID Create_Date
2 null 1 '2012-01-02'
2 1 2 '2012-01-03'
2 2 3 '2012-01-04'
2 3 1 '2012-01-05'
3 1 2 '2012-01-06'
2 2 3 '2012-01-10'
2 3 5 '2012-01-13'
2 5 1 '2012-01-22'
2 1 2 '2012-01-22'
This works fine:
with change_tree as
(
SELECT order_id,
previous_status_id,
next_status_id,
cast(next_status_id as varchar(max)) as status_path
FROM status_change
WHERE previous_status_id = 5
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))
FROM status_change sc
JOIN change_tree ct ON ct.next_status_id = sc.previous_status_id AND ct.order_id = sc.order_id
)
SELECT *
FROM change_tree
WHERE status_path = '5,1';
But if I modify it like so:
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
)
SELECT *
FROM change_tree
WHERE status_path = '1,2,3';
I get max recursion error.
This is kind of data that I'm expecting to get:
ORDER_ID StartDate EndDate
2 '2012-01-02' '2012-01-04'
2 '2012-01-05' '2012-01-10'
This will be done as a report. So I was thinking about storing results in another table and in the night doing only those orders that are new or for which sequence of statuses has ended.
So in my report table I must have those two records, and after adding next record to status_change table like:
ORDER_ID Previous_STATUS_ID Next_STATUS_ID Create_Date
2 2 3 '2012-02-25'
My procedure (function should add to report table only last sequence). Hope You'll get my point :)