问题
In this answer to What are the downsides of using SqlServer Views?, hyprsleepy suggests the ORDER BY
clause is not honoured in views in SQL Server.
Could anyone explain why this is the case?
Edit: Thanks for the answers, but I'm not sure thats the issue. I know you cant add an Order By Clause to a view and I dont have a problem with that, you just add it to the SELECT
statement when calling the view, but my impression from the other question was that using an Order By Clause in a SELECT
statement on a view will not give the correct results every time.
回答1:
SQL Server
developers assume that any set operation may change the order of the records so there is no point to use ORDER BY
in the intermediate set definitions and it only makes sense in the final statements.
The views may be used in joins or other operations which invalidates their orders.
Since you cannot use the view by itself, i. e. you don't write vMyView
, you rather write SELECT * FROM vMyView
, despite the fact that the view is a SELECT
per se, you can (and should) append the ORDER BY
clause to the SELECT
statement as well if you need an order.
This is quite a sane assumption and in fact it makes the code more clear.
回答2:
Take a look at Create a sorted view in SQL Server 2005 and SQL Server 2008
There is a way to do it but it is not supported, just issue an order by when selecting from the view
回答3:
In your view definition include TOP 100 PERCENT as a workaround. You can then use ORDER BY.
EDIT or as SQLMenace pointed out TOP 99.99 PERCENT.
回答4:
From wikipedia:
Just as rows in a base table lack any defined ordering, rows available through a view do not appear with any default sorting. A view is a relational table, and the relational model defines a table as a set of rows. Since sets are not ordered - by definition - the rows in a view are not ordered, either. Therefore, an ORDER BY clause in the view definition is meaningless.
回答5:
You can't put an ORDER BY clause in your views. The exact error is:
"The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP or FOR XML is also specified."
来源:https://stackoverflow.com/questions/5901558/is-order-by-honoured-in-sql-server-views