Refer below query.
SQL
DECLARE @Test AS TABLE(itId INT,itemName VARCHAR(20))
INSERT INTO @Test VALUES(1,'Apple')
INSERT INTO @Test VALUES(2,'pencil')
INSERT INTO @Test VALUES(3,'Mango')
INSERT INTO @Test VALUES(4,'pencil')
INSERT INTO @Test VALUES(5,'Banana')
INSERT INTO @Test VALUES(6,'')
INSERT INTO @Test VALUES(7,'Peach')
INSERT INTO @Test VALUES(8,'Stawbery')
DECLARE @Min INT,@Max INT
SET @Min = 3
SET @Max = ((SELECT itId FROM @Test WHERE ISNULL(itemName,'') = '') - 1)
SET @Max = COALESCE(NULLIF(@Max,''), @Max, @Min + 6)
SELECT TOP 6 * FROM @Test WHERE itId BETWEEN @Min AND @Max
Output
itId | itemName |
3 |
Mango |
4 |
pencil |
5 |
Banana |