在SELECT中使用已定义的变量会导致不正确的语法错误

时间:2021-07-07 21:13:03

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

不正确的语法@mynumber附近

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

我如何运行我的查询,使它像这样工作

SELECT TOP 15 * FROM mytable;

?

吗?

1 个解决方案

#1


4  

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

您可以从一个SQL查询中检索第一个N条记录以获取详细信息。

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

对于较老的版本,如SQL Server 2000,可以像这样使用ROWCOUNT

SET ROWCOUNT @mynumber
SELECT * FROM MyTable
SET ROWCOUNT 0

#1


4  

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

您可以从一个SQL查询中检索第一个N条记录以获取详细信息。

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

对于较老的版本,如SQL Server 2000,可以像这样使用ROWCOUNT

SET ROWCOUNT @mynumber
SELECT * FROM MyTable
SET ROWCOUNT 0