Wish to share some useful information related to data retrieval.
I got a recent query in dotnetspider site like, how to retrieve the data using rownumber concept. The user is not interested to fetch based on the data stored in the table but he wants to fetch based on the result set.
Problem scenario:
Irrespective of order by clause on any column, the user needs to retrieve the 50th row values.
Solution:
We have to map the row number for the entire result set and identify the 50th row values.
In the below code snippet, I’ve tried to create common table expression with rownumber() function[New in sql server 2005] order by address column. From the CTE, I’ve fetched the rownumber for the person "Arun" and display appropriate information for that particular row number.
Code Snippet |
DECLARE @VenkatTable TABLE (ID int, NAME varchar(50), ADDRESS varchar(50)) INSERT INTO @VENKATTABLE VALUES (1, 'Hari', 'Chennai') INSERT INTO @VENKATTABLE VALUES (2, 'Ram', 'Hyderabad') INSERT INTO @VENKATTABLE VALUES (3, 'Raj', 'Bombay') INSERT INTO @VENKATTABLE VALUES (52, 'Arun', 'Delhi') INSERT INTO @VENKATTABLE VALUES (53, 'Santhi', 'Dharmapuri') select * from @VenkatTable DECLARE @RowID int ;WITH VenkatTableCTE AS (SELECT ROW_NUMBER() OVER(ORDER BY Address) AS RowID, Name, Address FROM @VenkatTable) SELECT @RowID = RowID FROM VenkatTableCTE WHERE Name = 'Arun'; SELECT * from VenkatTableCTE WHERE RowID = @RowID |
Provide me your valuable feedback regarding this.
Regards,
Venkatesan Prabu . J
2 comments:
Hi Venkatesan's,
I was also looking for the same problem of finding the row number in sql server. By your this blog i am very happy to find the solution.
keep blogging.
My No: 09313770772
Thanks
Rahul
Hi Venkat,
It would be useful if you write one line comment in code snippet so that beginners like me would be able to relate the explanation and understand easily.
Thanks,
Parthiban
Post a Comment