如何在SQL Server 2005中使用LIMIT关键字?

时间:2022-04-10 15:32:36

I have found a way to select random rows from a table in this post. A suggestion is to use the following query:

我找到了一种从这篇文章中的表中选择随机行的方法。建议是使用以下查询:

SELECT * FROM employee ORDER BY RAND() LIMIT 1

But when I run this query in MS SQL 2005, I get the following error message

但是当我在MS SQL 2005中运行此查询时,我收到以下错误消息

Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'LIMIT'.

Can anyone tell me where am I wrong? Doesn't MS SQL support LIMIT? If so, then how can I do this?

谁能告诉我我错在哪里? MS SQL不支持LIMIT吗?如果是这样,那我该怎么办呢?

3 个解决方案

#1


44  

If you take a look at the SELECT statement in SQL Server Books Online, then you'll see that you can limit the resultset by using the TOP keyword.

如果您查看SQL Server联机丛书中的SELECT语句,那么您将看到可以使用TOP关键字限制结果集。

SELECT TOP 1 * FROM employee

#2


4  

SELECT TOP 1 * FROM Employee ORDER BY newid()

You have to use newid() for it to be evaluated once per row.

你必须使用newid()来每行评估一次。

#3


0  

I'm using this fairly simple one (SQL2005) to limit the number of rows returned, which will work with a value provided by a stored procedure parameter as well.

我使用这个相当简单的(SQL2005)来限制返回的行数,这也将与存储过程参数提供的值一起使用。

DECLARE @Limit int
SET @Limit = 10
SELECT TOP (@Limit) Col1, Col2 FROM SomeTable

#1


44  

If you take a look at the SELECT statement in SQL Server Books Online, then you'll see that you can limit the resultset by using the TOP keyword.

如果您查看SQL Server联机丛书中的SELECT语句,那么您将看到可以使用TOP关键字限制结果集。

SELECT TOP 1 * FROM employee

#2


4  

SELECT TOP 1 * FROM Employee ORDER BY newid()

You have to use newid() for it to be evaluated once per row.

你必须使用newid()来每行评估一次。

#3


0  

I'm using this fairly simple one (SQL2005) to limit the number of rows returned, which will work with a value provided by a stored procedure parameter as well.

我使用这个相当简单的(SQL2005)来限制返回的行数,这也将与存储过程参数提供的值一起使用。

DECLARE @Limit int
SET @Limit = 10
SELECT TOP (@Limit) Col1, Col2 FROM SomeTable