SQL SERVER – How to Access the Previous Row and Next Row value in SELECT statement? – Part 3

Earlier I wrote a blog post SQL SERVER – How to Access the Previous Row and Next Row value in SELECT statement? and SQL SERVER – How to Access the Previous Row and Next Row value in SELECT statement? – Part 2. In part 2 of the blog post, I wanted to write a solution which works with SQL Server 2000. In the solution I removed CTE but I forgot the detail that I SQL Server 2000 does not support RowNumber function as well. Thanks to smart blog readers who caught the error and immediately pointed that out in the comment area. Thank you so much for it. In this blog post, I will now demonstrate how to come up with the solution for previous row and next row in SQL Server 2000 version.  The question was that, how to get access to Previous Row and Next Row in the SELECT statement.

Let us assume that we have following SQL Query.

USE AdventureWorks2012
GO
SELECT p.FirstName
FROM Person.Person p
ORDER BY p.BusinessEntityID
GO

SQL SERVER - How to Access the Previous Row and Next Row value in SELECT statement? - Part 3 leadlagfunction

What we want is that in the same SELECT statement the previous row and next row should be listed. Additionally the solution should support SQL Server 2000 and later versions. Here is the solution for the same.

USE AdventureWorks2012
GO
SELECT
rownum = IDENTITY(INT, 1,1),
p.FirstName
INTO #TempTable
FROM Person.Person p
ORDER BY p.BusinessEntityID;
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

In the above example we have used Temp Table and with the help of Temp Table we have built our solution, which returns following result.

SQL SERVER - How to Access the Previous Row and Next Row value in SELECT statement? - Part 3 leadlagfunction1

I hope today I have got the answer correct with the help of Identity Function and Temp Table.

Reference: Pinal Dave (https://blog.sqlauthority.com)

SQL Function
Previous Post
SQL Contest – Hint for Identify the Database Celebrity
Next Post
SQL SERVER – How to Access the Previous Row and Next Row value in SELECT statement? – Part 4

Related Posts

Leave a Reply