Search This Blog

Friday, August 10, 2007

Display SQL records with Row Number

Select RowNum = (Select Count(1) From [Emp_Salary] EI
Where EI.[Emp_Id] <= EO.[Emp_Id]),
[E].[Emp_Name],
[E].[Emp_Sal]
From [Emp_Salary] EO

The Table should have at least one unique column which is Emp_ID in the above example.And also the above one displays the records in ascending order.

For descending order use the one which is below:
Select RowNum = (Select Count(1) From [Emp_Salary] EI
Where EI.[Emp_Id] >= EO.[Emp_Id]),
[E].[Emp_Name],
[E].[Emp_Sal]
From [Emp_Salary] EO

P.S:- Please note that SQL 2005 already has row number concept in built for which just use

select row_number() OVER(ORDER BY Emp_Id ),* from Emp_Salary

No comments: