MS SQL CTE HANGS HELP

Hello
I have the following scenarion.
I have a table with millions of records and I need to compare rows belonging to the same unitId to increment a counter
What I need to know is detect number that a unit changes from a certain set of color/description to another.
I Filter based on UnitId which is a varchar and a date, that would return thousands of rows from the main table.
Sometimes the CTE runs in les than 10 seconds and someother times it just hangs, that I have to stop the execution of the query even though it is the same query
Any idea what might be causing this hanging or maybe infinite loop somewhere as the sql server process would stick at 50% CPU when I look in task manager
Here is some sample code

Thanks
;
WITH CTE AS (
	SELECT top  ROW_NUMBER() OVER (ORDER BY UnitID, EventDate ) AS RowNum,
		UnitID, UnitDescription, EventDate,Color
	FROM UnitInfo 
    WHERE EventDate >='2000-01-01T00:00:00'
    AND UnitId LIKE 'veh-%'
)

SELECT  COUNT([Current Row].UnitID) AS C,[Current Row].UnitID
FROM CTE [Current Row]
LEFT JOIN CTE [Previous Row] 
  [Previous Row].RowNum = [Current Row].RowNum - 1
WHERE
	(([Previous Row].Color ='red' AND [Previous Row].UnitDescription='Merce')
	OR
	(
		(	[Previous Row].Color IN ('red','yellow','blue','white')
			AND
			([Current Row].Color IN ('Orange','Pink') OR [Current Row].UnitDescription='Golf')
		)
	))
	AND
	([Previous Row].UnitId = [Current Row].UnitId)
	
	GROUP BY [Current Row].UnitID

Open in new window

LVL 9
xav056Asked:
Who is Participating?
 
Raja Jegan RSQL Server DBA & Architect, EE Solution GuideCommented:
Try this which should work better:
;
WITH CTE AS (
	SELECT UnitID, ROW_NUMBER() OVER (ORDER BY UnitID, EventDate ) AS RowNum,
case when Color ='red' AND UnitDescription='Merce' then 1 else 0 end as cond_1,
case when Color IN ('Orange','Pink') OR UnitDescription='Golf' then 1 else 0 end as cond_2,
case when Color IN ('red','yellow','blue','white') then 1 else 0 end as cond_3
	FROM UnitInfo 
    WHERE EventDate >='2000-01-01T00:00:00'
    AND UnitId LIKE 'veh-%'
)

SELECT  COUNT([Current Row].UnitID) AS C,[Current Row].UnitID
FROM CTE [Current Row]
LEFT JOIN CTE [Previous Row] ON
  [Previous Row].RowNum = [Current Row].RowNum - 1
  AND [Previous Row].UnitId = [Current Row].UnitId
WHERE [Previous Row].cond_1 = 1
OR ( [Previous Row].cond_2 = 1 AND [Current Row].cond_3 = 1)
GROUP BY [Current Row].UnitID

Open in new window

0
 
xav056Author Commented:
Brilliant Thank you
0
 
Raja Jegan RSQL Server DBA & Architect, EE Solution GuideCommented:
Welcome..
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.