2010-08-26 77 views
2

我有一個存儲過程,它自己正常工作。最近的一項要求讓我覺得Union查詢將會完成我所需要的。這是工作版本。它使用ROW_NUMBER()來實現分頁和排序正確Tsql聯合查詢正在打破我的asp.net gridview排序

SELECT x.TicketID, 
x.TicketNumber, 
x.AccountID, 
x.SkillID 
FROM (
SELECT ROW_NUMBER() OVER(ORDER BY 
    CASE WHEN @ipv_SortExpression = 'TicketNumber' AND @ipv_SortDirection = 'ASC' THEN y.TicketNumber END ASC, 
    CASE WHEN @ipv_SortExpression = 'TicketNumber' AND @ipv_SortDirection = 'DESC' THEN y.TicketNumber END DESC,    
    CASE WHEN @ipv_SortExpression = 'AccountNumber' AND @ipv_SortDirection = 'ASC' THEN y.AccountNumber END ASC, 
    CASE WHEN @ipv_SortExpression = 'AccountNumber' AND @ipv_SortDirection = 'DESC' THEN y.AccountNumber END DESC,    
    CASE WHEN @ipv_SortExpression = 'OpenDate' AND @ipv_SortDirection = 'ASC' THEN y.OpenDate END ASC, 
    CASE WHEN @ipv_SortExpression = 'OpenDate' AND @ipv_SortDirection = 'DESC' THEN y.OpenDate END DESC       ) AS RowNumber, 
y.TicketID, 
y.TicketNumber, 
y.AccountID, 
y.SkillID 
FROM (SELECT 
    t.TicketID, 
    t.TicketNumber, 
    t.AccountID, 
    t.SkillID FROM someTable t) AS y 

) AS x WHERE x.RowNumber BETWEEN @startIdx AND @endIdx 

請注意我ommitted某些領域,縮短查詢。這可以正常工作,並且在調用該過程時,結果集將返回正確排序。現在我需要向結果集添加一條附加記錄。我嘗試了聯合查詢,但由於某些原因,它打破了排序,結果集總是以相同的順序返回...

SELECT x.TicketID, 
x.TicketNumber, 
x.AccountID, 
x.SkillID 
FROM (
SELECT ROW_NUMBER() OVER(ORDER BY 
    CASE WHEN @ipv_SortExpression = 'TicketNumber' AND @ipv_SortDirection = 'ASC' THEN y.TicketNumber END ASC, 
    CASE WHEN @ipv_SortExpression = 'TicketNumber' AND @ipv_SortDirection = 'DESC' THEN y.TicketNumber END DESC,    
    CASE WHEN @ipv_SortExpression = 'AccountNumber' AND @ipv_SortDirection = 'ASC' THEN y.AccountNumber END ASC, 
    CASE WHEN @ipv_SortExpression = 'AccountNumber' AND @ipv_SortDirection = 'DESC' THEN y.AccountNumber END DESC,    
    CASE WHEN @ipv_SortExpression = 'OpenDate' AND @ipv_SortDirection = 'ASC' THEN y.OpenDate END ASC, 
    CASE WHEN @ipv_SortExpression = 'OpenDate' AND @ipv_SortDirection = 'DESC' THEN y.OpenDate END DESC       ) AS RowNumber, 
y.TicketID, 
y.TicketNumber, 
y.AccountID, 
y.SkillID 
FROM (SELECT 
    t.TicketID, 
    t.TicketNumber, 
    t.AccountID, 
    t.SkillID FROM someTable t) AS y 

) AS x WHERE x.RowNumber BETWEEN @startIdx AND @endIdx 
    UNION 
SELECT 
    z.TicketID 
    z.TicketNumber 
    z.AccountID 
    z.SkillID 
FROM (

SELECT TOP 1 
    tix.biTicketID as TicketID 
    , tix.vcTicketID as TicketNumber 
    , tix.biAccountID as AccountID 
    , tix.siSkillID as SkillID 
FROM someOtherTable tix ORDER BY tix.ActionDate) As z 

此查詢斷裂排序我的網格。這就像程序完全忽略了我傳入的排序標準。我試圖先放置較小的查詢,然後聯合較大的查詢,但仍然沒有運氣。任何人都可以看到我做錯了什麼,或者我可以如何補救?客戶想要這個新功能,但他們不想犧牲排序。我如何正確完成我的任務?感謝任何建議或提示的一堆。

歡呼聲中,在聖地亞哥

回答

6

〜CK你需要一個ORDER BY對整個結果,如果你想要的結果進行排序集合。

(Query A) 
UNION 
(Query B) 
ORDER BY xxx 
+1

是的,ORDER BY RowNumber是所有需要在這裏結束 – SQLMenace 2010-08-26 20:44:40

+0

是的,順序rownumber似乎很好地工作。謝謝一堆! – Hcabnettek 2010-08-26 21:06:08