Equivalent of LIMIT and OFFSET for SQL Server?

前端 未结 16 1974
天命终不由人
天命终不由人 2020-11-22 06:07

In PostgreSQL there is the Limit and Offset keywords which will allow very easy pagination of result sets.

What is the equivalent syntax f

16条回答
  •  遥遥无期
    2020-11-22 06:44

    Since nobody provided this code yet:

    SELECT TOP @limit f1, f2, f3...
    FROM t1
    WHERE c1 = v1, c2 > v2...
    AND
        t1.id NOT IN
            (SELECT TOP @offset id
             FROM t1
             WHERE c1 = v1, c2 > v2...
             ORDER BY o1, o2...)
    ORDER BY o1, o2...
    

    Important points:

    • ORDER BY must be identical
    • @limit can be replaced with number of results to retrieve,
    • @offset is number of results to skip
    • Please compare performance with previous solutions as they may be more efficient
    • this solution duplicates where and order by clauses, and will provide incorrect results if they are out of sync
    • on the other hand order by is there explicitly if that's what's needed

提交回复
热议问题