简体   繁体   English

我可以在SQL Server数据库上使用LIMIT N,M吗

[英]Can I use LIMIT N,M on SQL Server database

I have the following SQL statement: 我有以下SQL语句:

SELECT [id], [name]
FROM [dbo.test_db_002] t1
LEFT JOIN [dbo.test_db_003] t2 ON t1.[id] = t2.[itmid]
ORDER BY t2.[iid] ASC;

This seems very simple, but I can't figure it out. 这似乎很简单,但我无法弄清楚。 I need to add LIMIT N,M to it to retrieve M items from the N'th one, but I keep getting errors around 'limit' word. 我需要在其中添加LIMIT N,M来从第N个项目中检索M个项目,但是我在'limit'单词周围一直遇到错误。 I tried putting that LIMIT clause everywhere I could inside the sql statement above with no avail. 我试图将LIMIT子句放在上面的sql语句中的任何地方,但无济于事。

PS. PS。 I'm writing for SQL Server that comes with VS2010. 我正在写VS2010附带的SQL Server。

To answer for your query, you may want: (depending on your values for M and N ) 要回答您的查询,您可能需要:(取决于您的MN值)

WITH cte AS
(
   SELECT [id], [name], ROW_NUMBER() OVER (ORDER BY t2.[iid] ASC) AS rowNumber
   FROM [dbo.test_db_002] t1
   LEFT JOIN [dbo.test_db_003] t2 ON t1.[id] = t2.[itmid]
)
SELECT [id], [name]
FROM cte
WHERE rowNumber BETWEEN 3 AND 5

Something to watch out for, the values in the between are BETWEEN N AND N + M 需要注意的是,介于两者之间的值介于BETWEEN N AND N + M

Also, here's a link with information about Common Table Expressions which is the WITH cte syntax I used. 另外,这是一个链接,其中包含有关公用表表达式的信息,这是我使用的WITH cte语法。

There's no direct equivalent to LIMIT N,M in SQL Server, but you can do something like this: 在SQL Server中没有与LIMIT N,M直接等效的方法,但是您可以执行以下操作:

SELECT * FROM
  (SELECT *, ROW_NUMBER() OVER (ORDER BY name) as row FROM MyTable) a
WHERE row > 5 and row <= 10

See here for some more info: "LIMIT" in SQL Server 有关更多信息,请参见此处: SQL Server中的“ LIMIT”

You could use Row_Number() 您可以使用Row_Number()

example: 例:

select * from 
(
  select cola, colb, row_number() over (order by col1 desc) as row
  from table ) x
where row between value1 and value2

Limit with offset in sql server 2012: 在SQL Server 2012中具有偏移量的限制:

SELECT email FROM myTable
OFFSET 10 ROWS
FETCH NEXT 10 ROWS ONLY;

//offset - no. //偏移量-不。 of skipped rows 跳过的行数

//next - required no. // next-不需要 of next rows 下一行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM