development

SQL Server의 LIMIT 10..20

big-blog 2020. 6. 7. 00:46
반응형

SQL Server의 LIMIT 10..20


나는 다음과 같은 일을하려고합니다.

SELECT * FROM table LIMIT 10,20

또는

SELECT * FROM table LIMIT 10 OFFSET 10

그러나 SQL Server 사용

내가 찾은 유일한 솔루션 은 과잉처럼 보입니다.

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

나는 또한 발견했다 :

SELECT TOP 10 * FROM stuff; 

...하지만 시작 한계를 지정할 수 없기 때문에 내가하고 싶은 것이 아닙니다.

내가 할 수있는 또 다른 방법이 있습니까?

또한 궁금한 점이 있는데 SQL Server가 LIMIT함수 또는 이와 유사한 기능을 지원하지 않는 이유가 있습니까? 나는 의미가되고 싶지 않지만 DBMS가 필요로하는 것처럼 들린다. 만약 그렇다면, 그렇게 무지한 것이 유감 스럽다! 지난 5 년간 MySQL 및 SQL +와 함께 일해 왔습니다.


LIMIT절은 표준 SQL의 일부가 아닙니다. MySQL, PostgreSQL 및 SQLite에서 SQL에 대한 공급 업체 확장으로 지원됩니다.

다른 브랜드의 데이터베이스는 유사한 기능 (예 : TOPMicrosoft SQL Server)을 가질 수 있지만 항상 동일하게 작동하지는 않습니다.

조항 TOP을 모방하기 위해 Microsoft SQL Server에서 사용하기가 어렵습니다 LIMIT. 작동하지 않는 경우가 있습니다.

사용하여 표시 한 솔루션 ROW_NUMBER()은 Microsoft SQL Server 2005 이상에서 사용할 수 있습니다. 이것은 쿼리의 일부로 만 작동하는 (현재로서는) 최상의 솔루션입니다.

또 다른 해결책은 TOP첫 번째 카운트 + 오프셋 행을 가져온 다음 API를 사용하여 첫 번째 오프셋 행을 지나서 찾는 것 입니다.

또한보십시오:


SQL Server 2012 +의 경우을 사용할 수 있습니다 .

SELECT  *
FROM     sys.databases
ORDER BY name 
OFFSET  5 ROWS 
FETCH NEXT 5 ROWS ONLY 

알다시피, 이것은 선호되는 SQL 서버 방법입니다.

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

Martin Smith의 답변에 대해 SQL Server 2012 이상 투표를 사용 OFFSET하고에 FETCH NEXT확장명을 사용하는 경우 ORDER BY,

불행히도 이전 버전을 고수 할 수 있다면 다음과 같이 할 수 있습니다.

WITH Rows AS
(
    SELECT
              ROW_NUMBER() OVER (ORDER BY [dbo].[SomeColumn]) [Row]
            , *
        FROM
              [dbo].[SomeTable]
)
SELECT TOP 10
          *
     FROM
         Rows
    WHERE Row > 10

나는 기능적이라고 생각합니다

SELECT * FROM SomeTable LIMIT 10 OFFSET 10 ORDER BY SomeColumn

그리고 MS SQL 2012 이전에 TSQL에서 내가 아는 최고의 성능.


행이 매우 많은 경우 CTE 대신 임시 테이블을 사용하여 성능을 향상시킬 수 있습니다.


Unfortunately, the ROW_NUMBER() is the best you can do. It's actually more correct, because the results of a limit or top clause don't really have meaning without respect to some specific order. But it's still a pain to do.

Update: Sql Server 2012 adds a limit -like feature via OFFSET and FETCH keywords. This is the ansi-standard approach, as opposed to LIMIT, which is a non-standard MySql extension.


How about this?

SET ROWCOUNT 10 

SELECT TOP 20 *
FROM sys.databases
ORDER BY database_id DESC

It gives you the last 10 rows of the first 20 rows. One drawback is that the order is reversed, but, at least it's easy to remember.


SELECT TOP 10 *
FROM TABLE
WHERE IDCOLUMN NOT IN (SELECT TOP 10 IDCOLUMN FROM TABLE)

Should give records 11-20. Probably not too efficient if incrementing to get further pages, and not sure how it might be affected by ordering. Might have to specify this in both WHERE statements.


A good way is to create a procedure:

create proc pagination (@startfrom int ,@endto int) as
SELECT * FROM ( 
  SELECT *, ROW_NUMBER() OVER (ORDER BY name desc) as row FROM sys.databases 
 ) a WHERE a.row > @startfrom and a.row <= @endto

just like limit 0,2 /////////////// execute pagination 0,4


Just for the record solution that works across most database engines though might not be the most efficient:

Select Top (ReturnCount) *
From (
    Select Top (SkipCount + ReturnCount) *
    From SourceTable
    Order By ReverseSortCondition
) ReverseSorted
Order By SortCondition

Pelase note: the last page would still contain ReturnCount rows no matter what SkipCount is. But that might be a good thing in many cases.


The equivalent of LIMIT is SET ROWCOUNT, but if you want generic pagination it's better to write a query like this:

;WITH Results_CTE AS
(
    SELECT
        Col1, Col2, ...,
        ROW_NUMBER() OVER (ORDER BY SortCol1, SortCol2, ...) AS RowNum
    FROM Table
    WHERE <whatever>
)
SELECT *
FROM Results_CTE
WHERE RowNum >= @Offset
AND RowNum < @Offset + @Limit

select * from (select id,name,ROW_NUMBER() OVER (ORDER BY id  asc) as row
from tableName1) tbl1
where tbl1.row>=10 and tbl1.row<=15

Will print rows from 10 to 15.


So far this format is what is working for me (not the best performance though):

SELECT TOP {desired amount of rows} * 
FROM (SELECT *, ROW_NUMBER() OVER (ORDER BY {order columns} asc)__row__ FROM {table})tmp
WHERE __row__ > {offset row count}

A note on the side, paginating over dynamic data can lead to strange/unexpected results.


From the MS SQL Server online documentation (http://technet.microsoft.com/en-us/library/ms186734.aspx ), here is their example that I have tested and works, for retrieving a specific set of rows. ROW_NUMBER requires an OVER, but you can order by whatever you like:

WITH OrderedOrders AS
(
  SELECT SalesOrderID, OrderDate,
  ROW_NUMBER() OVER (ORDER BY OrderDate) AS RowNumber
  FROM Sales.SalesOrderHeader 
) 
SELECT SalesOrderID, OrderDate, RowNumber  
FROM OrderedOrders 
WHERE RowNumber BETWEEN 50 AND 60;

Use all SQL server: ;with tbl as (SELECT ROW_NUMBER() over(order by(select 1)) as RowIndex,* from table) select top 10 * from tbl where RowIndex>=10


 SELECT * FROM users WHERE Id Between 15 and 25

it will print from 15 to 25 as like limit in MYSQl

참고URL : https://stackoverflow.com/questions/971964/limit-10-20-in-sql-server

반응형