How to sort within a sql view

∥☆過路亽.° 提交于 2019-12-08 16:01:35

问题


I've created a sql view and I need to sort the results of select by using the ORDER BY on 4 fields, but I'm getting message that ORDER BY cannot be used in views unless I use TOP. Can someone explain why TOP is needed, and does someone have a workaround for sorting in a sql view?

Thanks.


回答1:


you don't need to sort a view. a view is like a table so you sort it when you select from it:

select * from yourView order by yourColumns



回答2:


There is no guarantee the output of the view will be ordered

Only the outermost ORDER BY applies for result sets: not any inner ones. So only this ORDER BY can be guaranteed to work:

SELECT col1, col2, FROm MyView ORDER BY col2

You can add it to views or derived tables and it forces "intermediate materialisation" because the results have to be ordered. However, for SQL Server 2005 and above, you have to use TOP 2000000000 not TOP 100 PERCENT (except for that HF that Daniel Vassallo mentioned!)

Someone will use your view with a different order to that internally at some point too.




回答3:


You can try:

CREATE VIEW View_Products
AS
SELECT ProductID, ProductName, UnitPrice, CreateDate FROM Products
Order by CreateDate DESC
OFFSET 0 ROWS



回答4:


Would creating an index on the column with which you intend to sort the view help?




回答5:


If using SQL Server, you can do

select top 100 percent * 
from MyTable 
order by MyColumn

Of course you shouldn't use an * in your view, I just used it here for brevity.



来源:https://stackoverflow.com/questions/2010276/how-to-sort-within-a-sql-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!