March 04, 2008

Passing parameter to the TOP clause

The TOP clause in SQL Server 2005 has been enhanced. You can now specify an expression as the number definition in the TOP clause. This makes your TOP clause dynamic as you can pass the number value in a variable and use that variable in the TOP clause of your T-Sql query

Sample Usage:

DECLARE @TopVar AS int
SET @TopVar = 20

CustomerID,CompanyName, ContactName
FROM Northwind.dbo.Customers

Did you like this post?
kick it on
subscribe via rss subscribe via e-mail
print this post follow me on twitter

About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal



6 Responses to "Passing parameter to the TOP clause"
  1. Anonymous said...
    August 20, 2008 at 9:03 AM

    it is very good.It solve my problem.

  2. Anonymous said...
    October 21, 2008 at 4:27 AM

    Have you had any luck using this in a VS2005 report?

  3. Suprotim Agarwal said...
    October 22, 2008 at 9:44 AM

    I do not think that should be any problem. Are you facing one?

  4. Anonymous said...
    March 12, 2009 at 9:05 PM

    I am attempting to use this in VS2005 writing a Reporting Services report.

    However, I am receiving the error "The number of rows in a TOP clause must be an integer".

    The parameter within the report is set as an integer. It seems VS is sending the parameter value as something other than an integer?

  5. Christophe Vanderhaeghen said...
    January 7, 2011 at 2:17 AM

    It's indeed a clean and easy solution, but there is a catch: it works really slow and for larger tables you'll notice significant performance-loss!

    My 2 cents

  6. Praveen said...
    January 14, 2011 at 9:03 PM

    For SQL SERVER 2000, there is workaround and please take a look at it here.


Copyright © 2009-2016 All Rights Reserved for by Suprotim Agarwal | Terms and Conditions