Search code examples
sqlsql-servert-sql

How do I get records before and after given one?


I have the following table structure:

Id, Message
1, John Doe
2, Jane Smith
3, Error
4, Jane Smith

Is there a way to get the error record and the surrounding records? i.e. find all Errors and the record before and after them.


Solution

  • ;WITH numberedlogtable AS
    (
    SELECT Id,Message, 
    ROW_NUMBER() OVER (ORDER BY ID) AS RN
     FROM logtable
    )
    
    SELECT Id,Message
    FROM numberedlogtable
    WHERE RN IN (SELECT RN+i
                 FROM numberedlogtable
                 CROSS JOIN (SELECT -1 AS i UNION ALL SELECT 0 UNION ALL SELECT 1) n
                 WHERE Message='Error')