SQL顺序/案例问题:订单方向失败

时间:2010-04-25 11:47:53

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

我有一个存储过程,提供一个学生表,它需要按姓氏,名称等排序......它还需要按升序,降序排序,具体取决于参数@orderby ...

代码:

ORDER BY
CASE 
 WHEN @orderby = 'studentkey' THEN Studentkey END ASC,
CASE 
 WHEN @orderby = 'studentkey' and @desc = 1 THEN Studentkey END DESC,
CASE
 WHEN @orderby = 'initials' THEN Initials END ASC,
CASE
 WHEN @orderby = 'initials' and @desc = 1 THEN Initials END DESC,
CASE
 WHEN @orderby = 'firstname' THEN Firstname END ASC,
CASE
 WHEN @orderby = 'firstname' and @desc = 1 THEN Firstname END DESC,
CASE
 WHEN @orderby = 'nickname' THEN Nickname END ASC,
CASE
 WHEN @orderby = 'nickname' and @desc = 1 THEN Nickname END DESC, 
CASE
 WHEN @orderby = 'insertion' THEN Insertion END ASC,
CASE
 WHEN @orderby = 'insertion' and @desc = 1 THEN Insertion END DESC,
CASE
 WHEN @orderby = 'surname' THEN Surname END ASC,
CASE
 WHEN @orderby = 'surname' and @desc = 1 THEN Surname END DESC
NED

@desc = 1和@desc = 0之间的输出存在差异,但不是我想要的......

有没有人有解决方案?

1 个答案:

答案 0 :(得分:1)

试试这个:

CASE 
 WHEN @orderby = 'studentkey' and @desc = 0 THEN Studentkey END ASC,
CASE 
 WHEN @orderby = 'studentkey' and @desc = 1 THEN Studentkey END DESC,
...