sql:除非另外還指定了 TOP 或 FOR XML,否則,ORDER BY 子句在視圖、內聯函數、派生表、子查詢
執行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,
CREATE VIEW dbo.VSortedOrders AS SELECT orderid, customerid FROM dbo.Orders ORDER BY orderid GO
那麼可能會遇到下麵的錯誤
消息 1033,級別 15,狀態 1,第 4 行 除非另外還指定了 TOP 或 FOR XML,否則,ORDER BY 子句在視圖、內聯函數、派生表、子查詢和公用表表達式中無效。
原因就是針對一個表的SELECT其實並不是返回一個表,而是一個遊標。
如果一定要用怎麼辦呢?答案就是配合TOP 100 PERCENT
SELECT TOP (100) PERCENT orderid, customerid FROM dbo.Orders ORDER BY orderid, customerid DESC
最後更新:2017-04-03 12:56:05