Row Offset in SQL Server

后端 未结 16 2541
醉酒成梦
醉酒成梦 2020-11-22 05:53

Is there any way in SQL Server to get the results starting at a given offset? For example, in another type of SQL database, it\'s possible to do:

SELECT * FR         


        
16条回答
  •  孤城傲影
    2020-11-22 06:24

    This is one way (SQL2000)

    SELECT * FROM
    (
        SELECT TOP (@pageSize) * FROM
        (
            SELECT TOP (@pageNumber * @pageSize) *
            FROM tableName 
            ORDER BY columnName ASC
        ) AS t1 
        ORDER BY columnName DESC
    ) AS t2 
    ORDER BY columnName ASC
    

    and this is another way (SQL 2005)

    ;WITH results AS (
        SELECT 
            rowNo = ROW_NUMBER() OVER( ORDER BY columnName ASC )
            , *
        FROM tableName 
    ) 
    SELECT * 
    FROM results
    WHERE rowNo between (@pageNumber-1)*@pageSize+1 and @pageNumber*@pageSize
    

提交回复
热议问题