sql order by错top(100)percent

来源:互联网 发布:怎么在淘宝找客户资料 编辑:程序博客网 时间:2024/06/04 19:45

执行sql语句:

select * from (

select * from tab where ID>20 order by userID desc

) as a order by date desc


逻辑上看着挺对 但是报错:

除非另外还指定了 TOP 或 FOR XML,否则,ORDER BY 子句在视图、内联函数、派生表、子查询和公用表表达式中无效。


只要我们在嵌套子查询视图里面加入: top 100 percent 即可

select * from (

select top 100 percent * from tab where ID>20 order by userID desc

) as a order by date desc



默认情况下,如果在子查询,函数,视图中尝试去使用ORDER BY,

<span class="kwrd" style="color: rgb(0, 0, 255);">CREATE</span> <span class="kwrd" style="color: rgb(0, 0, 255);">VIEW</span> dbo.VSortedOrders<span class="kwrd" style="color: rgb(0, 0, 255);">AS</span><span class="kwrd" style="color: rgb(0, 0, 255);">SELECT</span> orderid, customerid<span class="kwrd" style="color: rgb(0, 0, 255);">FROM</span> dbo.Orders<span class="kwrd" style="color: rgb(0, 0, 255);">ORDER</span> <span class="kwrd" style="color: rgb(0, 0, 255);">BY</span> orderidGO

 

那么可能会遇到下面的错误

消息 1033,级别 15,状态 1,第 4 行除非另外还指定了 <span class="kwrd" style="color: rgb(0, 0, 255);">TOP</span> 或 <span class="kwrd" style="color: rgb(0, 0, 255);">FOR</span> XML,否则,<span class="kwrd" style="color: rgb(0, 0, 255);">ORDER</span> <span class="kwrd" style="color: rgb(0, 0, 255);">BY</span> 子句在视图、内联函数、派生表、子查询和公用表表达式中无效。
<strong>原因就是针对一个表的SELECT其实并不是返回一个表,而是一个游标。</strong>
 
如果一定要用怎么办呢?答案就是配合TOP 100 PERCENT
<span class="kwrd" style="color: rgb(0, 0, 255);">SELECT</span>     <span class="kwrd" style="color: rgb(0, 0, 255);">TOP</span> (100) <span class="kwrd" style="color: rgb(0, 0, 255);">PERCENT</span> orderid, customerid<span class="kwrd" style="color: rgb(0, 0, 255);">FROM</span>         dbo.Orders<span class="kwrd" style="color: rgb(0, 0, 255);">ORDER</span> <span class="kwrd" style="color: rgb(0, 0, 255);">BY</span> orderid, customerid DESC

0 0
原创粉丝点击