DECLARE @eventID INT DECLARE evtcursor CURSOR FOR SELECT ID FROM Event ORDER BY ID OPEN evtcursor FETCH NEXT FROM evtcursor INTO @eventID WHILE @@FETCH_STATUS = 0 BEGIN DECLARE @count INT ; WITH cte AS ( SELECT ROW_NUMBER() OVER(PARTITION BY evtdata.SeriesID ORDER BY evtdata.Time) [Index], evtdata.* FROM GetEventData(@eventID) evtdata JOIN Series ON evtdata.SeriesID = Series.ID JOIN Channel ON Series.ChannelID = Channel.ID WHERE Channel.MeasurementCharacteristicID = 34 ) SELECT @count = COUNT(*) FROM cte cte1 JOIN cte cte2 ON cte1.SeriesID = cte2.SeriesID AND cte2.[Index] = cte1.[Index] + 1 WHERE cte1.Value = 0 AND cte2.Value <> 0 INSERT INTO StatusChatter VALUES(@eventID, @count) FETCH NEXT FROM evtcursor INTO @eventID END