serves a purpose beyond the usual presentation purpose. Even standard SQL has a similar restriction,
some people think that they can create “ordered views.” One of the ways to try to achieve this is by
For example, run the following query against the view.
Here is the output from one of my executions showing that the rows are not sorted by region.
172
Microsoft SQL Server 2012 T-SQL Fundamentals
In some cases, a query that is used to define a table expression has the TOP option with an ORDER
BY clause, and the query against the table expression doesn’t have an ORDER BY clause. In those cases,
therefore, the output might or might not be returned in the specified order. If the results happen to
be ordered, it may be due to optimization reasons, especially when you use values other than TOP
(100) PERCENT. The point I’m trying to make is that any order of the rows in the output is considered
valid, and no specific order is guaranteed; therefore, when querying a table expression, you should
not assume any order unless you specify an ORDER BY clause in the outer query.
In SQL Server 2012, there’s a new way to try to get a “sorted view,” by using the OFFSET clause with
0 ROWS, and without a
FETCH clause, like the following.
ALTER VIEW Sales.USACusts
AS
SELECT
custid, companyname, contactname, contacttitle, address,
city, region, postalcode, country, phone, fax
FROM Sales.Customers
WHERE country = N'USA'
ORDER BY region
OFFSET 0 ROWS;
GO
At the moment, when I query the view and don’t indicate an ORDER BY clause in the outer query,
the result rows happen to be sorted by region. But I stress—
do not assume that that’s guaranteed.
It happens to be the case due to current optimization. If you need a guarantee that the rows will be
returned from the query against the view sorted, you need an ORDER BY clause in the outer query.
Do not confuse the behavior of a query that is used to define a table expression with a query
that isn’t. A query with an ORDER BY clause and a TOP or OFFSET-FETCH option does not guarantee
presentation order only in the context of a table expression. In the context of a query that is not used
to define a table expression, the ORDER BY clause serves both the filtering purpose for the TOP or
OFFSET-FETCH option and the presentation purpose.
Do'stlaringiz bilan baham: