SQL Server 2008 R2分页

时间:2011-02-02 06:46:15

标签: sql sql-server tsql sql-server-2008 pagination

我需要为我的联合查询实现分页,但是我收到错误“消息102,级别15,状态1,行14 ')'附近的语法不正确。“。我按照link找到的示例。

select * 
  from (select Id, 
               row_number() OVER (order by Id asc) as RowNumber 
          from (select Id 
                  from (select Id 
                          from Table1) as table1 
                union all 
                select Id 
                  from (select Id 
                          from Table2) as table2)) as t Derived 
  WHERE RowNumber > 5 
    and RowNumber <= 10

4 个答案:

答案 0 :(得分:3)

使用:

SELECT u.* 
  FROM (SELECT t.id, 
               ROW_NUMBER() OVER (ORDER BY t.id) as rownum 
          FROM (SELECT t1.id 
                  FROM TABLE1 t1
                UNION ALL 
                SELECT t2.id 
                  FROM TABLE2 t2) as t) AS u
 WHERE u.rownum > 5 
   AND u.rownum <= 10

在我看来,您的查询缺少一个名为“derived”的派生表的结束括号,但是UNION中不需要子查询,所以我删除了它们。

答案 1 :(得分:1)

您只需要移动一个括号:

from Table2) as table2)) as t Derived应该阅读from Table2) as table2) as t) Derived

您还可以删除一些将Table1放入table1和Table2放入table2的子查询,但我假设其中有一些其他的reaon(就像这是基于另一个更复杂的查询)

答案 2 :(得分:1)

select * 
  from (select Id, 
               row_number() OVER (order by Id asc) as RowNumber 
          from (select Id 
                  from Table1 as table1 
                union all 
                select Id 
                  from Table2)p)t 
  WHERE RowNumber > 5 
    and RowNumber <= 10

答案 3 :(得分:0)

如果从子查询中选择,则必须为其提供别名。您有2个外部子查询,但只有一个具有别名。应该是:from Table2) as tabl2) as t) as t