Login or Sign Up to become a member!
LessThanDot Sit Logo

LessThanDot

Community Wiki

Less Than Dot is a community of passionate IT professionals and enthusiasts dedicated to sharing technical knowledge, experience, and assistance. Inside you will find reference materials, interesting technical discussions, and expert tips and commentary. Once you register for an account you will have immediate access to the forums and all past articles and commentaries.

LTD Social Sitings

Lessthandot twitter Lessthandot Linkedin Lessthandot friendfeed Lessthandot facebook Lessthandot rss

Note: Watch for social icons on posts by your favorite authors to follow their postings on these and other social sites.

Navigation

Google Ads

Return Top N Rows

From Wiki

Jump to: navigation, search

You want to give users the ability to return 5, 10, 20 or any number of rows where they can supply the number. In SQL Server 2005 you can now use TOP with a variable. IN SQL Server 2000 you have to use SET ROWCOUNT

SQL Server 2000 version.

Create this table

  1. CREATE TABLE #TopTest(SomeValue VARCHAR(53))
  2.      
  3.     INSERT #TopTest VALUES(1)
  4.     INSERT #TopTest VALUES(2)
  5.     INSERT #TopTest VALUES(3)
  6.     INSERT #TopTest VALUES(4)
  7.     INSERT #TopTest VALUES(5)
  8.     INSERT #TopTest VALUES(6)
  9.     INSERT #TopTest VALUES(7)
  10.     INSERT #TopTest VALUES(8)


Return the top 5 rows ascending

  1. DECLARE @TOP INT
  2.     SELECT @TOP =5
  3.     SET ROWCOUNT @TOP
  4.      
  5.     SELECT *
  6.     FROM #TopTest
  7.     ORDER BY SomeValue
  8.      
  9.     SET ROWCOUNT 0


Return the top 5 rows descending

  1. DECLARE @TOP INT
  2.     SELECT @TOP =5
  3.     SET ROWCOUNT @TOP
  4.      
  5.     SELECT *
  6.     FROM #TopTest
  7.     ORDER BY SomeValue DESC
  8.      
  9.     SET ROWCOUNT 0


Make sure that you set the ROWCOUNT back to 0 after the query because it might mess up later statements


SQL Server 2005 version.

First create this table

  1. CREATE TABLE #TopTest(SomeValue VARCHAR(53))
  2.      
  3.     INSERT #TopTest VALUES(1)
  4.     INSERT #TopTest VALUES(2)
  5.     INSERT #TopTest VALUES(3)
  6.     INSERT #TopTest VALUES(4)
  7.     INSERT #TopTest VALUES(5)
  8.     INSERT #TopTest VALUES(6)
  9.     INSERT #TopTest VALUES(7)
  10.     INSERT #TopTest VALUES(8)


Return the top 5 rows descending

  1. DECLARE @TOP INT
  2.     SELECT @TOP =5
  3.      
  4.     SELECT TOP (@TOP) *
  5.     FROM #TopTest
  6.     ORDER BY SomeValue


Return the top 5 rows descending

  1. DECLARE @TOP INT
  2.     SELECT @TOP =5
  3.      
  4.     SELECT TOP (@TOP) *
  5.     FROM #TopTest
  6.     ORDER BY SomeValue DESC


Contributed by: --SQLDenis 02:09, 31 May 2008 (GMT)

Part of SQL Server Programming Hacks

Section Sorting, Limiting

128 Rating: 2.2/5 (9 votes cast)