CTE选择按动态排序列名称

时间:2017-07-12 08:56:56

标签: sql-server

;with cte as select * from customer

通过传递参数

来选择cte顺序
if(@orderby=1)
  begin
    select * from cte order by name
  end
 else if (@oderby=2)
  begin
     select * from cte order by applydate   
  end
 else
    begin
     select * from cte order by customeramount
    end

以下错误无效对象cte如何解决此sql查询

我必须解决问题

代码是

 SELECT * FROM cte ORDER BY CASE @OrderBy WHEN 0 THEN Name ELSE null END , CASE  @OrderBy WHEN 1 THEN  Code ELSE null END ,CASE @OrderBy  WHEN 2 THEN  ApplyAmountTotal ELSE null END ,CASE @OrderBy WHEN 3 THEN ApplyDate ELSE null END 

3 个答案:

答案 0 :(得分:1)

您可以使用以下案例:

;With cte as 
(   select * from customer  )
Select * from cte 
    Order by (case when @orderby=1 then [name]
                   when @orderby=2 then applydate
                   else customerAmount end )

答案 1 :(得分:0)

nameapplydatecustomerAmount的数据类型不同, 那么你可以使用像这样的3 CASE ...END个条款

SELECT * 
FROM customer 
ORDER BY        
        CASE
          WHEN @oderby = 1 THEN name          
          ELSE ''
        END,
        CASE
          WHEN @oderby = 2 THEN applydate
          ELSE '1900-01-01'
        END,
        CASE
          WHEN @oderby NOT IN (1,2) THEN customerAmount
          ELSE 1
        END

答案 2 :(得分:0)

我找到答案

SELECT * FROM cte ORDER BY CASE @OrderBy WHEN 0 THEN Name ELSE null END , CASE  @OrderBy WHEN 1 THEN  Code ELSE null END ,CASE @OrderBy  WHEN 2 THEN  ApplyAmountTotal ELSE null END ,CASE @OrderBy WHEN 3 THEN ApplyDate ELSE null END