博客 / 詳情

返回

SQL Server中視圖關於ORDER BY的限制

SQL Server數據庫中在視圖中使用ORDER BY是有限制的, 如下所示:

CREATE VIEW Maint.V_BlockingSQLHistory
AS
SELECT [RecordTime],[DatabaseName], [Blocking_SessionId],[Blocked_SessionId]
FROM [Maint].[BlockingSQLHistory]
ORDER BY [RecordTime];

如果在視圖中這樣使用ORDER BY,就會遇到錯誤提示信息.如下所示

Msg 1033, Level 15, State 1, Procedure V_BlockingSQLHistory, Line 5 [Batch Start Line 0]
The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified.

其實也不是説視圖中絕對不能使用ORDER BY,而是使用ORDER BY是有條件的,除非你同時指定了TOP, OFFSET, FOR XML子句. 如果將上面視圖改成下面這樣就OK.

CREATE VIEW Maint.V_BlockingSQLHistory
AS
SELECT TOP 10 [RecordTime],[DatabaseName], [Blocking_SessionId],[Blocked_SessionId]
FROM [Maint].[BlockingSQLHistory]
ORDER BY [RecordTime];

官方文檔的解釋/介紹如下:

The ORDER BY clause isn't valid in views, inline functions, derived tables, and subqueries, unless either the TOP or OFFSET 
and FETCH clauses are also specified. When ORDER BY is used in these objects, the clause is used only to determine the rows 
returned by the TOP clause or OFFSET and FETCH clauses. The ORDER BY clause doesn't guarantee ordered results when these constructs
 are queried, unless ORDER BY is also specified in the query itself.

在視圖、內聯函數、派生表和子查詢中,ORDER BY 子句是無效的,除非同時指定了TOP 或 OFFSET 和 FETCH 子句。當在這些對象中使用 ORDER BY 時,
該子句僅用於確定由 TOP 子句或 OFFSET 和 FETCH 子句返回的行。除非在查詢本身中也指定了 ORDER BY,否則這些構造被查詢時,ORDER BY 子句不能
保證結果的有序性。

參考資料

https://learn.microsoft.com/en-us/sql/t-sql/queries/select-order-by-clause-transact-sql?view=sql-server-ver17&redirectedfrom=MSDN

user avatar u_16120231 頭像 u_15365254 頭像 zxsoft 頭像 mpanda 頭像 u_14035463 頭像 yangjunfeng 頭像 RCJL 頭像 actionopensource 頭像
8 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.