我使用以下SP来分页新闻文章。正如您可能猜到的那样,@count
是要返回的行数,@start
是从中选择行的索引(按内部查询排序),@orderby
表示要排序的列by,和@orderdir
表示是否对一个方向或另一个方向进行排序。我的原始查询是
在我添加@orderdir
参数之前here。
ALTER PROCEDURE [mytable].[news_editor_paginate]
@count int,
@start int,
@orderby int,
@orderdir int
AS
BEGIN
SET NOCOUNT ON;
SELECT TOP (@count) * FROM
(
SELECT ne.*,n.publishstate,
(CASE WHEN @orderdir = 1 THEN
ROW_NUMBER() OVER (
ORDER BY
CASE WHEN @orderby = 0 THEN ne.[time] END DESC,
CASE WHEN @orderby = 1 THEN ne.lastedit END DESC,
CASE WHEN @orderby = 2 THEN ne.title END ASC
)
WHEN @orderdir = 2 THEN
ROW_NUMBER() OVER (
ORDER BY
CASE WHEN @orderby = 0 THEN ne.[time] END ASC,
CASE WHEN @orderby = 1 THEN ne.lastedit END ASC,
CASE WHEN @orderby = 2 THEN ne.title END DESC
)
END
) AS num
FROM news_edits AS ne
LEFT OUTER JOIN news AS n
ON n.editid = ne.id
)
AS a
WHERE num > @start
END
现在没有任何问题,但@orderby
参数不起作用。如果提供1作为@orderdir
参数,它将给出与我提供2作为该参数完全相同的结果。
答案 0 :(得分:17)
行数不会在每一行上进行评估,但是case语句是这样的,无论如何你都会被rownum所困扰。
请改为尝试:
ROW_NUMBER() OVER (
ORDER BY
CASE WHEN @orderby = 0 AND @orderdir = 1 THEN ne.[time] END DESC,
CASE WHEN @orderby = 0 AND @orderdir = 2 THEN ne.[time] END ASC,
CASE WHEN @orderby = 1 AND @orderdir = 1 THEN ne.lastedit END DESC,
CASE WHEN @orderby = 1 AND @orderdir = 2 THEN ne.lastedit END ASC,
CASE WHEN @orderby = 2 AND @orderdir = 1 THEN ne.title END ASC
CASE WHEN @orderby = 2 AND @orderdir = 2 THEN ne.title END DESC
)
答案 1 :(得分:1)
这对我来说很好 - (在哪里,顺序,方向,偏移获取)
-- parameters
@orderColumn int ,
@orderDir varchar(20),
@start int ,
@limit int
select * from items
WHERE (items.status = 1)
order by
CASE WHEN @orderColumn = 0 AND @orderdir = 'desc' THEN items.[category] END DESC,
CASE WHEN @orderColumn = 0 AND @orderdir = 'asc' THEN items.[category] END ASC,
CASE WHEN @orderColumn = 1 AND @orderdir = 'desc' THEN items.[category] END DESC,
CASE WHEN @orderColumn = 1 AND @orderdir = 'asc' THEN items.[category] END ASC,
CASE WHEN @orderColumn = 2 AND @orderdir = 'desc' THEN items.[category] END DESC,
CASE WHEN @orderColumn = 2 AND @orderdir = 'asc' THEN items.[category] END ASC
OFFSET @start ROWS FETCH NEXT @limit ROWS ONLY