使用OFFSET和FETCH进行分页的通用顺序

时间:2014-10-09 23:40:20

标签: sql-server-2012

我正在尝试生成通用订单。

CREATE TABLE #TempTable
    (col1 varchar(3)));

    DECLARE @sql nvarchar(max)
    DECLARE @SkipRows int
    DECLARE @FetchRows int 
    DECLARE @Idlist varchar(100)

        SET @Idlist = '10,14,16,20,23,28,21,36,24,36,35,39,32,31,33'


        SET @sql = N'SELECT  a.col1 AS FROM tbl a (nolock) WHERE a.col1 IN(' + @Idlist +') ORDER BY (SELECT 0) '
                    + 'OFFSET  ' + @SkipRows  + '  ROWS  FETCH NEXT ' + @FetchRows  + ' ROWS ONLY '

INSERT INTO #TempTable ([col1])
    EXEC(@sql)

在上面的查询中

**如果我订了     @SkipRows = 2和@FetchRows = 4然后我想看到如下结果:

  OrderNum   col1
     3          16
     4          20
     5          23
     6          28

**      如果我设置@SkipRows = 6和@FetchRows = 2然后我想看到如下结果:

OrderNum   col1
 7          21
 8          36

注意:OrderNum不是我表格中的列。

1 个答案:

答案 0 :(得分:2)

您缺少a.col1的列别名,并且必须将SkipRows和FetchRows变量强制转换为varchar以进行连接,或者像这样使用CONCAT:

SET @sql = CONCAT(N'
    SELECT 
       OrderNum = ROW_NUMBER() OVER (ORDER BY (SELECT 0)), 
       a.col1 AS col1 
    FROM tbl a (nolock) 
       WHERE a.col1 IN (',@Idlist, N') 
    ORDER BY (SELECT 0) OFFSET ', @SkipRows, N' ROWS FETCH NEXT ',
    @FetchRows, N' ROWS ONLY '
    )

当我尝试它时,这似乎有效(因为我得到了预期的结果):

对于@SkipRows = 2 and @FetchRows = 4

得到:

OrderNum             col1
-------------------- -----------
3                    16
4                    20
5                    23
6                    28

@SkipRows = 6 and @FetchRows = 2得到:

OrderNum             col1
-------------------- -----------
7                    21
8                    36