Saturday, June 1, 2019

Getting LEAD and LAG values manually in SQLServer2008R2 or earlier versions (SQL Developer)


Getting Previous and  next values is always a need for any database professional, specially Analyst and Developers, SQL Server provide built in Functions for this purpose which are introduced in SQL Server 2012, This Script is useful to get same results in Earlier versions like 2008, 2008R2 etc.

Let’s create a Table and insert some dummy records for Demo.
CREATE TABLE Employee
(
Empid int NOT NULL,
Name nchar(10) NULL,
City nchar(10) NULL
) ON [PRIMARY]
GO

Inserting Dummy Records
Insert into Employee
Values(1245,'George','Jax'), (1045,'Peter','Anadale'), (1157,'John','Dallas'),
      (1175,'Pete','Topeka'), (875,'Petron','Vienna'), (2311,'Kohli','Mumbai'),
      (1547,'Peter','Kansas'), (3514,'Abian','KHI'), (4251,'Ghani','Alexandria'),
      (957,'Ahmed','Vienna'), (1084,'Bhanu','Manderin'), (2954,'Ganeshan','Mcclean')
     




Displaying Previous Values LAG Function



Displaying Next Values LEAD Function



Other Developer related blogs
table data comparison
sqlcmd export data to txt
sql analytical functions
script to generate foreign keys
convert values into rows