Row Offset in SQL Server

后端 未结 16 2536
醉酒成梦
醉酒成梦 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:38

    For tables with more and large data columns, I prefer:

    SELECT 
      tablename.col1,
      tablename.col2,
      tablename.col3,
      ...
    FROM
    (
      (
        SELECT
          col1
        FROM 
        (
          SELECT col1, ROW_NUMBER() OVER (ORDER BY col1 ASC) AS RowNum
          FROM tablename
          WHERE ([CONDITION])
        )
        AS T1 WHERE T1.RowNum BETWEEN [OFFSET] AND [OFFSET + LIMIT]
      )
      AS T2 INNER JOIN tablename ON T2.col1=tablename.col1
    );
    

    -

    [CONDITION] can contain any WHERE clause for searching.
    [OFFSET] specifies the start,
    [LIMIT] the maximum results.
    

    It has much better performance on tables with large data like BLOBs, because the ROW_NUMBER function only has to look through one column, and only the matching rows are returned with all columns.

提交回复
热议问题