Earlier I wrote a blog post SQL SERVER – How to Access the Previous Row and Next Row value in SELECT statement?. Right after the blog post was published I received an email from SQL Server users who have no access to CTE and wanted me to help him out with the solution as well. Absolutely, Here is the solution for the anyone who is using SQL Server 2005 and does not use CTE.
I strongly suggest you read my earlier blog post before continuing this blog post as they are related to each other. 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.
FROM Person.Person p
ORDER BY p.BusinessEntityID
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 2005 and later versions. Here is the solution for the same.
CREATE TABLE #TempTable (rownum INT, FirstName VARCHAR(256));
INSERT INTO #TempTable (rownum, FirstName)
rownum = ROW_NUMBER() OVER (ORDER BY p.BusinessEntityID),
FROM Person.Person p;
FROM #TempTable TT
LEFT JOIN #TempTable prev ON prev.rownum = TT.rownum - 1
LEFT JOIN #TempTable nex ON nex.rownum = TT.rownum + 1;
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.
UPDATE: I had a few inaccuracies in the blog post, which is corrected based on the feedback of users. Thanks!
Reference: Pinal Dave (https://blog.sqlauthority.com)