SQL 如何从T-SQL中的表中选择前N行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1552021/
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 select first N rows from a table in T-SQL?
提问by dragan.stepanovic
Is there any way to select, for example, first 10 rows of a table in T-SQL (working MSSQL)?
I think I saw something in Oracle defined as rownum meta variable, used in a following way
有什么方法可以选择,例如,T-SQL(工作 MSSQL)中表的前 10 行?
我想我在 Oracle 中看到了一些定义为 rownum 元变量的东西,使用方式如下
select * from Users where rownum<=10但是 MSSQL 呢?
回答by Mehrdad Afshari
select top(@count) * from users
If @count
is a constant, you can drop the parentheses:
如果@count
是常量,则可以去掉括号:
select top 42 * from users
(the latter works on SQL Server 2000 too, while the former requires at least 2005)
(后者也适用于 SQL Server 2000,而前者至少需要 2005)
回答by Jonathan
You can use Microsoft's row_number() function to decide which rows to return. That means that you aren't limited to just the top X results, you can take pages.
您可以使用 Microsoft 的 row_number() 函数来决定要返回哪些行。这意味着您不仅限于前 X 个结果,您还可以获取页面。
SELECT *
FROM (SELECT row_number() over (order by UserID) AS line_no, *
FROM dbo.User) as users
WHERE users.line_no < 10
OR users.line_no BETWEEN 34 and 67
You have to nest the original query though, because otherwise you'll get an error message telling you that you can't do what you want to in the way you probably should be able to in an ideal world.
但是,您必须嵌套原始查询,否则您将收到一条错误消息,告诉您您无法按照在理想世界中应该能够做到的方式做您想做的事情。
Msg 4108, Level 15, State 1, Line 3
Windowed functions can only appear in the SELECT or ORDER BY clauses.
回答by LukeH
回答by ChickenMilkBomb
You can also use rowcount, but TOP is probably better and cleaner, hence the upvote for Mehrdad
你也可以使用 rowcount,但 TOP 可能更好更干净,因此对 Mehrdad 的支持
SET ROWCOUNT 10
SELECT * FROM dbo.Orders
WHERE EmployeeID = 5
ORDER BY OrderDate
SET ROWCOUNT 0
回答by Rameshwar Pawale
Try this.
尝试这个。
declare @topval int
set @topval = 5 (customized value)
SELECT TOP(@topval) * from your_database
回答by Rahul
SELECT TOP 10 * FROM TABLE_NAMEORDER BY ORDERED_UNIQUE_COLUMNDESC
SELECT TOP 10 * FROM TABLE_NAMEORDER BY ORDERED_UNIQUE_COLUMNDESC
ORDERED_UNIQUE_COLUMNcould be your incrementing primary key or a timestamp
ORDERED_UNIQUE_COLUMN可能是您递增的主键或时间戳
回答by RPL
Try this:
尝试这个:
SELECT * FROM USERS LIMIT 10;