Saturday, 11 June 2016

Fetch Next and Previous rows values in SQL Server.


Description:



In this example we explain that how to fetch next and previous rows values in SQL Server.or get the next and previous record from table in sql server.

There are many question arise in mind like is there any ways to access the “previous row” and “next row” value in SELECT statement in SQL Server.sql has no inbuilt facility to access next and previous rows of the table.



So below is the SQL Query to access the previous Row and Next Row value in SELECT statement.

CREATE TABLE# TempTable(rownum INT, FirstName VARCHAR(256));
INSERT INTO# TempTable(rownum, FirstName)
SELECT
rownum = ROW_NUMBER() OVER(ORDER BY p.BusinessEntityID),
    p.FirstName
FROM Person.Person p;
SELECT
prev.FirstName PreviousValue,
    TT.FirstName,
    nex.FirstName NextValue
FROM# TempTable TT
LEFT JOIN# TempTable prev ON prev.rownum = TT.rownum - 1
LEFT JOIN# TempTable nex ON nex.rownum = TT.rownum + 1;
GO

This entry was posted in :

0 comments:

Post a Comment