Undetermined sort order when using ROW_NUMBER() OVER decimal column with ties

喜你入骨 提交于 2019-12-10 20:31:12

问题


I have a very strange bug with sql server 2008:

To display a pager in a CRUD application details view, I make a sql request to get previous and next record relative to the current, it works well except when ordering on a DECIMAL column, I can reduce the problem to that query (FTE is decimal(18,2)):

WITH [IndexedRows] AS (
    SELECT 
        [ContactId], 
        [ContactCode],
        [FTE],
        [EmployeeName], 
        ROW_NUMBER() OVER ( ORDER BY [FTE] ASC ) AS [RowIndex]
    FROM   
        [Vw_HrEmployee]
)

/* 1. I can see ContactId 1109 is rowindex 7 */
/*SELECT * FROM [IndexedRows];*/

/* 2. Get the RowIndex, it returns 7 */
/*SELECT [RowIndex] 
FROM   [IndexedRows] 
WHERE  [ContactId] = 1109;*/

/* 3. Why it doesn't returns ContactId 1109 ??? */
SELECT [ContactId], 
       [EmployeeName] 
FROM   [IndexedRows] 
WHERE [RowIndex] = 7;

I get the contactId of another person who have the same FTE value, but I don't understand why the WHERE rowindex don't return the correct row (if I display IndexedRows, it looks good!).

I don't think it's revelant but Vw_HrEmployee is a View.

Any help/idea/workaround to solve that is welcome,

Thanks in advance


回答1:


This is a guess, but if you have duplicate values for the FTE value then there is no guarantee as to which order they will come out in each time that the code is run. SQL Server is probably changing the query plan between when you do a simple SELECT and a SELECT with the WHERE criteria, causing a different order to come out and what you are seeing.

I would add the PK onto the end of your ORDER BY just to ensure that the ordering is always consistent.




回答2:


Perhaps add another sort criteria to help ensure the correct/desired order?

ROW_NUMBER() OVER ( ORDER BY [FTE] ASC, 
                             BirthDate ASC, 
                             AstrologySign DESC ) AS [RowIndex] 


来源:https://stackoverflow.com/questions/7919325/undetermined-sort-order-when-using-row-number-over-decimal-column-with-ties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!