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

About The Author

Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigous Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook


Anonymous said...

it is very good.It solve my problem.

Anonymous said...

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

Suprotim Agarwal said...

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

Anonymous said...

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?

Christophe Vanderhaeghen said...

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

Praveen said...

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