DECLARE @GroupIdPrevious BIGINT, @GroupRankPrevious BIGINT
DECLARE @GroupId BIGINT, @GroupRank BIGINT
SET @GroupId = 2
DECLARE GroupAssignmentCursor CURSOR FAST_FORWARD FOR
SELECT
GroupID
,GroupRank
FROM
#GroupAssignment
WHERE
GroupId = @GroupId
OPEN GroupAssignmentCursor
FETCH NEXT FROM GroupAssignmentCursor INTO @GroupIdPrevious, @GroupRankPrevious
IF @@FETCH_STATUS = 0
BEGIN
FETCH NEXT FROM GroupAssignmentCursor INTO @GroupId, @GroupRank
WHILE @@FETCH_STATUS = 0
BEGIN
IF @GroupRank - @GroupRankPrevious = 1 -- There is no gap
BEGIN
SET @GroupIdPrevious = @GroupId
SET @GroupRankPrevious = @GroupRank
FETCH NEXT FROM GroupAssignmentCursor INTO @GroupId, @GroupRank
END
ELSE
BEGIN
SELECT @GroupIdPrevious AS GroupIdPrevious, @GroupRankPrevious AS GroupRankPrevious, @GroupId AS GroupId, @GroupRank AS GroupRank, 'Found gap' AS OutputMsg
BREAK
END
END
END
CLOSE GroupAssignmentCursor
DEALLOCATE GroupAssignmentCursor
======================================================================
Another way is to a loop with Cursor. here are the steps (I am just typing this - you need to make sure the syntax is correct)
- Declare the cursor
- Fetch the 1st row
- Save the Id in a local variable (Previous Id)
- Fetch the 2nd row
- Start a WHILE Loop WHEN NOT EOF (@@FETCH_STATUS....)
- Compare the Current Id with the Previous Id
- If the difference is 1 skip
- if not set the value or print
- Fetch Next
If you are interested, I can write the complete code and post it
Ravi Ramaswamy