SQL: Unless you also specify TOP or for XML, the ORDER by clause is in view, inline function, derived table, subquery

Source: Internet
Author: User

Execute SQL statement:

SELECT * FROM (

SELECT * from tab where id>20 order by UserID Desc

As a order by date desc

Logically looking pretty right but error:

The ORDER by clause is not valid in views, inline functions, derived tables, subqueries, and common table expressions unless you specify also TOP or for XML.

As long as we add in the nested subqueries view: Top percent

SELECT * FROM (

Select Top Percent * from Tab where id>20 order by UserID Desc

As a order by date desc

By default, if you try to use ORDER by in a subquery, function, view,

VIEW dbo. Vsortedordersas SELECT OrderID, CustomerID fromdbo. Orders byOrderidgo   

Then you may encounter the following error

For XML, otherwise, the byclause is invalid in views, inline functions, derived tables, subqueries, and common table expressions. 
The reason is that a select for a table does not actually return a table, but rather a cursor.
What if it must be used? The answer is to match top PERCENT
SELECT     PERCENT OrderID, CustomerIDfrom         dbo. Ordersby OrderID, CustomerID DESC  

SQL: Unless you also specify TOP or for XML, the ORDER by clause is in view, inline function, derived table, subquery

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.