Question

I have declared a variable that gives me an integer number:

Let's say the variable is defined like this:

DECLARE @mynumber int;
SET @mynumber = 15;

And now I would like to use this number in a query like this:

SELECT TOP @mynumber * 
FROM mytable;

And I get an error that says:

Incorrect syntax near @mynumber

How can I run my query so that it will work like

SELECT TOP 15 * FROM mytable;

?

Was it helpful?

Solution

You may simply try like this:

SELECT TOP(@mynumber) * 
FROM mytable;

You may check Retrieving the First N Records from a SQL Query for details

For older version like SQL Server 2000 you can use ROWCOUNT as like

SET ROWCOUNT @mynumber
SELECT * FROM MyTable
SET ROWCOUNT 0
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top