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

Dynamic TOP

From Wiki

Jump to: navigation, search

How can you use a variable with top? First create this table

  1. CREATE TABLE #Test (id INT)
  2.     INSERT #Test VALUES (1)
  3.     INSERT #Test VALUES (2)
  4.     INSERT #Test VALUES (3)
  5.     INSERT #Test VALUES (4)
  6.     INSERT #Test VALUES (5)
  7.     INSERT #Test VALUES (6)


Yoo want to run this but you would like the user to supply a parameter instead of 3

  1. SELECT TOP 3 *
  2.     FROM #Test
  3.     ORDER BY ID


In SQL Server 2005 you can use TOP with a variable. SELECT TOP (@var) FROM.... The variable has to be enclosed in parentheses, they are required Example

  1. DECLARE @TOP INT
  2.     SELECT @TOP = 3
  3.     SELECT TOP (@TOP) * FROM #Test
  4.     ORDER BY ID


For the SQl Server 2000 version we can use SET ROWCOUNT (this has been deprecated in SQL Server 2005)

Example

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


Make sure to reset ROWCOUNT to 0 after the select since it might affect any other DML operations you have below this code


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

Part of SQL Server Programming Hacks

Section Sorting, Limiting

129 Rating: 1.6/5 (7 votes cast)