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.
I am getting the above said error while trying to execute the following query. Can anyone please have a look and tell me what am I doing wrong here?
SELECT
*
FROM (
SELECT
Stockmain.VRNOA,
item.description as item_description,
party.name as party_name,
stockmain.vrdate,
stockdetail.qty,
stockdetail.rate,
stockdetail.amount,
ROW_NUMBER() OVER (ORDER BY VRDATE) AS RowNum
FROM StockMain
INNER JOIN StockDetail
ON StockMain.stid = StockDetail.stid
INNER JOIN party
ON party.party_id = stockmain.party_id
INNER JOIN item
ON item.item_id = stockdetail.item_id
WHERE stockmain.etype='purchase'
ORDER BY VRDATE DESC
) AS MyDerivedTable
WHERE
MyDerivedTable.RowNum BETWEEN 1 and 5
4条答案
按热度按时间vsikbqxv1#
You do not need to use
ORDER BY
in inner query afterWHERE
clause because you have already used it inROW_NUMBER() OVER (ORDER BY VRDATE DESC)
.vxqlmq5t2#
Surprisingly makes it work, what a strange feature.
A bigger example with a CTE as a way to temporarily "store" a long query to re-order it later:
So we get all results ordered by
MainCol
But the results with
MainCol = 1
get ordered byColX
And the results with
MainCol = 0
get ordered byColY
py49o6xq3#
In my case, I was using an "Inline Table-Valued User Defined Function" and trying to do an order by. And I was getting below exception:
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.
Solution I changed it to Multiline Statement Table-Values Function and it started working.
To do so instead of returning the data straightaway from the SQL,
eqoofvh94#
Adding a select top xyz worked in my case.