CTE表达式中的TSQL-ORDER BY子句?

时间:2017-11-08 03:18:58

标签: sql sql-server tsql stored-procedures

我们可以在CTE表达式中使用ORDER BY子句吗?

;with y as
(
     select 
         txn_Date_Time, txn_time, card_No, batch_No, terminal_ID
     from 
         C1_Transaction_Information
     where 
         txn_Date_Time = '2017-10-31'
     order by 
         card_No
)
select * from y;

错误讯息:

  

Msg 1033,Level 15,State 1,Line 14
  除非还指定了TOP,OFFSET或FOR XML,否则ORDER BY子句在视图,内联函数,派生表,子查询和公用表表达式中无效。

     

Msg 102,Level 15,State 1,Line 25
  ','。

附近的语法不正确

3 个答案:

答案 0 :(得分:2)

您不能在CTE中使用“Order By”,但您可以将订单移至调用CTE的select语句并具有我认为您正在寻找的影响

;with y as(
select txn_Date_Time,txn_time,card_No,batch_No,terminal_ID
from C1_Transaction_Information
where txn_Date_Time='2017-10-31'

)

select * from y order by card_No;

答案 1 :(得分:1)

FYI https://docs.microsoft.com/en-us/sql/t-sql/queries/with-common-table-expression-transact-sql

  

以下条款不能用于CTE_query_definition:

     

ORDER BY(指定TOP子句时除外)

     

INTO

     带有查询提示的

OPTION子句

     

FOR BROWSE

答案 2 :(得分:0)

一个好的选择是在CTE中使用ROW_NUMBER:

;with y as
(
     select  
         rn = ROW_NUMBER() OVER (ORDER BY card_No),
         txn_Date_Time, 
         txn_time, 
         card_No, 
         batch_No, 
         terminal_ID
     from 
         C1_Transaction_Information
     where 
         txn_Date_Time = '2017-10-31'
)
select txn_Date_Time, 
         txn_time, 
         card_No, 
         batch_No, 
         terminal_ID
from y 
order by rn;

这使您可以选择将TOP 10选为TOP ...在CTE中不允许使用ORDER BY:

;with y as
(
     select  
         rn = ROW_NUMBER() OVER (ORDER BY card_No),
         txn_Date_Time, 
         txn_time, 
         card_No, 
         batch_No, 
         terminal_ID
     from 
         C1_Transaction_Information
     where 
         txn_Date_Time = '2017-10-31'
)
select txn_Date_Time, 
         txn_time, 
         card_No, 
         batch_No, 
         terminal_ID
from y 
where rn <= 10;