Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server - use a parameter to select the top X of the result set [duplicate]

Tags:

sql-server

I am creating a SQL Server query that will take a parameter and use that as the record number to return.

In pseudo code:

parameter returnCount  select top returnCount * from table where x = y 

What is the correct syntax/code to perform that operation?

like image 386
pithhelmet Avatar asked Jun 08 '11 21:06

pithhelmet


People also ask

How does SELECT top work in SQL?

Limits the rows returned in a query result set to a specified number of rows or percentage of rows in SQL Server. When you use TOP with the ORDER BY clause, the result set is limited to the first N number of ordered rows. Otherwise, TOP returns the first N number of rows in an undefined order.

What is an alternative for top clause in SQL?

There is an alternative to TOP clause, which is to use ROWCOUNT. Use ROWCOUNT with care, as it can lead you into all sorts of problems if it's not turned off.

How does SQL Server top 1 work?

What does TOP 1 mean in an sql query? It means take only the first n rows. You need an "order by" to define what the first rows will be.


2 Answers

In SqlServer 2005 and up, do this:

CREATE PROCEDURE GetResults    (     @ResultCount   int ) AS  SELECT top(@ResultCount) FROM table where x = y 

For earlier versions, use:

CREATE PROCEDURE GetResults    (     @ResultCount   int ) AS  SET ROWCOUNT @ResultCount  SELECT * FROM table where x = y 

http://www.4guysfromrolla.com/webtech/070605-1.shtml for more information.

like image 51
agent-j Avatar answered Sep 16 '22 22:09

agent-j


As of SQL Server 2005 (but not before that), you can define a variable to determine your number of TOP rows returned:

DECLARE @returnCount INT  SET @returnCount = 15  SELECT TOP (@returnCount) *  FROM dbo.table  WHERE x = y 
like image 29
marc_s Avatar answered Sep 17 '22 22:09

marc_s