2011-02-02 167 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