我正在尝试根据输入参数对行进行排序,但它总是按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
请帮我找到解决这个问题的方法。
答案 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