SQL Server 2012 has many enhanced features, one is OFFSET FETCH clause. To fetch second row or any specific row from an ordered result of SQL query we can use this feature of SQL Server. We can fetch specific row from ordered result set using only single statement as I explained below.
I have one table which has employee information as shown below
Result of above query:
OFFSET FETCH Clause
The OFFSET-FETCH clause provides us option to fetch only a window or page of results from the result set. The only limitation is, you can use this with ORDER BY clause only. That make sense actually, if we want second row of a result set it means some order should present from which we want second rowI have one table which has employee information as shown below
SELECT [ID] ,[Name] ,[Post] FROM [JPDB].[dbo].[Employee]Result of above query is:
Below is the SQL script using OFFSET FETCH to get 2nd row of a result
SELECT [ID] ,[Name] ,[Post] FROM [JPDB].[dbo].[Employee] ORDER BY [ID] ASC OFFSET 1 ROWS FETCH NEXT 1 ROWS ONLYThe number I have written after OFFSET skips rows, and the number written after NEXT get total number of rows
Result of above query:
Suppose I want 2nd and 3rd row then below is the query:
SELECT [ID] ,[Name] ,[Post] FROM [JPDB].[dbo].[Employee] ORDER BY [ID] ASC OFFSET 1 ROWS FETCH NEXT 2 ROWS ONLYResult:
No comments:
Post a Comment