2011-02-02 172 views
1

我需要为我的联合查询实现分页,但出现错误“Msg 102,Level 15,State 1,Line 14 ''''附近的语法不正确。我跟着我从这个link发现的例子。SQL Server 2008 R2分页

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 
+0

发生了什么事?你有错误吗? – Axarydax 2011-02-02 06:49:11

+0

已更新的答案包含错误消息。 – newbie 2011-02-02 06:51:21

+0

我从来不喜欢SQL Server的错误位置,但我在代码中计算了12行。你有没有粘贴过什么? – donkim 2011-02-02 06:55:00

回答

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 

在我看来,你的查询失踪了所谓的“衍生”派生表右括号,但没有必要在UNION子查询所以我删除了它们。

0

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

1

你只需要动一个括号:

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

你也可以去除一些,使表1至表1和表2中表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