Though ordering is not needed other than in row_number if only one record returned by the query. but
You can try adding TOP
keyword. Note that TOP 100 PERCENT
does not work. you can try adding TOP 9999999
(maximum) possible number.
Also some comment in OP suggests that No need to add order by because of ORDER BY
in ROW_NUMBER
but ROW_NUMBER
does not order rows always (reference : https://msdn.microsoft.com/en-in/library/ms186734.aspx. check General Remarks).
There is no guarantee that the rows returned by a query using
ROW_NUMBER() will be ordered exactly the same with each execution
You can refer couple of helpful articles:
http://blog.sqlauthority.com/2010/08/23/sql-server-order-by-does-not-work-limitation-of-the-views-part-1/
Create a view with ORDER BY clause
Edit:
other solution is use a variable instead of constant in TOP
keyword.
for example TOP (@T) PERCENT
.
declare @t as tinyint = 100
declare @tbl as table (num1 int,num2 int)
insert into @tbl values (7,1),(2,7),(4,6),(6,4), (7,1),(2,7),(4,6),(6,4)
select * from(select top 100 percent * from @tbl order by num1) t
select * from(select top (@t) percent * from @tbl order by num1) t
In above example the last query gives expected result. If there is a variable in TOP keyword, the SQL assumes there could be any value so it will always consider it instead of ignoring it.