DROP TABLE #Results
DECLARE @UserID int
SET @UserID = 10
select
*,
ROW_NUMBER() OVER(ORDER BY Score DESC) AS RowNum
INTO #Results
from result
DECLARE @UserNo int, @MinNum int, @MaxNum int
SELECT @UserNo = RowNum
FROM #Results
WHERE UserID = @UserID
SELECT @MinNum = CASE WHEN @UserNo > 3 THEN @UserNo - 3 ELSE @UserNo END
SELECT @MaxNum = @MinNum + 6
DECLARE @Diff int
SELECT @Diff = @MaxNum - MAX(RowNum)
FROM #Results
SELECT @MaxNum = CASE WHEN @Diff > 0 THEN MAX(RowNum) ELSE @MaxNum END
FROM #Results
SELECT @MinNum = CASE WHEN @Diff > 0 THEN @MinNum - @Diff ELSE @MinNum END
SELECT *
FROM #Results
WHERE RowNum >= @MinNum AND Rownum <= @MaxNum
|