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

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.

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

Reference: Pinal Dave (http://blog.SQLAuthority.com)

About these ads

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

  1. Pingback: SQL SERVER – How to Access the Previous Row and Next Row value in SELECT statement? – Part 4 | Journey to SQL Authority with Pinal Dave

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s