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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With