SQL Server 2008:Row_Number()始终对ASC进行排序

时间:2017-09-07 13:15:44

标签: sql-server sql-server-2008 tsql sql-order-by

我正在尝试根据输入参数对行进行排序,但它总是按ASC顺序排序。

CREATE PROCEDURE SP_NAME
    @order VARCHAR(4),
    @col VARCHAR(100),
    @locationId int,
AS
BEGIN
    SELECT 
        ROW_NUMBER() OVER (ORDER BY
                                   CASE WHEN @order = 'asc' AND @col = 'Time' 
                                           THEN [Time] 
                                   END ASC,
                                   CASE WHEN @order = 'desc' AND @col = 'Time' 
                                           THEN [Time] 
                                   END DESC) AS Row#,
        Col1, COl2, COl3,
    FROM 
        Table_ 
    WHERE 
        ID = @locationid
END

EXEC SP_NAME 'asc', 'Time' > Sorting in ASC
EXEC SP_NAME 'desc', 'Time' > Sortin in ASC

请帮我找到解决这个问题的方法。

2 个答案:

答案 0 :(得分:1)

无法保证ROW_NUMBER()语句会对结果集进行排序,您应该执行以下操作:

SELECT 
    ROW_NUMBER() OVER (ORDER BY
                               CASE WHEN @order = 'asc' AND @col = 'Time' 
                                       THEN [Time] 
                               END ASC,
                               CASE WHEN @order = 'desc' AND @col = 'Time' 
                                       THEN [Time] 
                               END DESC) AS Row#,
    Col1, COl2, COl3,
FROM 
    Table_ 
WHERE 
    ID = @locationid
ORDER BY Row# ASC

答案 1 :(得分:0)

SELECT 
    Row# = CASE WHEN @order = 'DESC' THEN 
                ROW_NUMBER() OVER (ORDER BY
                               CASE WHEN @col = 'Time' THEN 
                                        [Time] 
                               END DESC) 
            ELSE
                ROW_NUMBER() OVER (ORDER BY
                               CASE WHEN @col = 'Time' THEN 
                                        [Time] 
                               END ASC) 
            END,
    Col1, COl2, COl3,
FROM 
    Table_ 
WHERE 
    ID = @locationid