如何在 SQL Server 2005 中使用 LIMIT 关键字?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/455008/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use LIMIT keyword in SQL Server 2005?
提问by user11445
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 吗?如果是这样,那么我该怎么做?
回答by Frederik Gheysels
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
回答by Jonas Lincoln
SELECT TOP 1 * FROM Employee ORDER BY newid()
You have to use newid() for it to be evaluated once per row.
您必须使用 newid() 才能每行评估一次。
回答by Stuntbeaver
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