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

Mos*_*han 3 sql t-sql sql-server stored-procedures

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

;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;
Run Code Online (Sandbox Code Playgroud)

错误信息:

消息 1033,级别 15,状态 1,第 14 行
ORDER BY 子句在视图、内联函数、派生表、子查询和公用表表达式中无效,除非还指定了 TOP、OFFSET 或 FOR XML。

消息 102,级别 15,状态 1,第 25 行
“,”附近的语法不正确。

小智 5

您不能在 CTE 中使用“Order By”,但您可以将 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;
Run Code Online (Sandbox Code Playgroud)


why*_*heq 5

一个不错的选择是在 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;
Run Code Online (Sandbox Code Playgroud)

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

;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;
Run Code Online (Sandbox Code Playgroud)