我有一个select语句,结尾如下:
order by case @pcsort
when '' then compcode asc
else received asc, compcode asc
end
基本上我需要它,如果@pcsort
是'',那么按compcode
排序,否则按received
和compcode
按顺序排序。
有什么想法吗?
答案 0 :(得分:7)
这将做你想要的假设数据类型是兼容的
order by
case @pcsort
when '' then compcode
else received
end ASC,
compcode ASC
更一般地说,假设数据类型兼容
,每个排序列需要一个CASEorder by
case @pcsort
when '' then compcode
else received
end ASC,
case @pcsort
--safe to sort on same column agaon , or use a constant
when '' then compcode or <constant of same type as compcode>
else compcode
end ASC
如果数据类型不兼容,则需要更多案例和大量常量
order by
case @pcsort
when '' then compcode
else <constant of same type as compcode>
end ASC,
case @pcsort
when '' then <constant of same type as received>
else received
end ASC,
case @pcsort
when '' then <constant of same type as compcode>
else compcode
end ASC