我需要按照我的视图中的两个表中包含的日期列进行排序。下面是我用于视图的语法,但如果我尝试在视图中使用order by语句,则会出现此错误:
Msg 1033,Level 15,State 1,Procedure TransFund_Lead_Upload_File,Line 63
ORDER BY子句在视图,内联函数,派生表和子查询中无效,除非还指定了TOP。
这是我的查询语法..需要改变什么,以便我可以通过[Follow Up] Desc来订购?
SELECT * FROM
(
Select
'abcd' As [P]
,ISNULL(Building_Name,'') As [Building_Name]
,ISNULL(ID,'') As [Record ID]
,ISNULL(city,'') + ', ' + ISNULL([state],'') As [Zone]
,ISNULL(CONVERT(VARCHAR(10), [Sale Date], 101),'') As [Actual Sale Date]
,'' As [Begin Effort]
,ISNULL(CAST(sold_items AS VARCHAR(500)),'') As [Items List]
,ISNULL(CAST(wascoreItemSold AS Varchar(500)),'') As [Info]
,ISNULL(CONVERT(VARCHAR(10), followupdate, 101),'') As [Follow Up]
FROM dbo.esrt b
UNION ALL
Select
'eeee' As [P]
,ISNULL(Building_Name,'') As [Building_Name]
,ISNULL(ID,'') As [Record ID]
,ISNULL(city,'') + ', ' + ISNULL([state],'') As [Zone]
,ISNULL(CONVERT(VARCHAR(10), Sale Date, 101),'') As [Actual Sale Date]
,'' As [Begin Effort]
,ISNULL(CAST(sold_items AS Varchar(500)),'') As [Items List]
,ISNULL(CAST(wascoreItemSold AS Varchar(500)),'') As [Info]
,ISNULL(CONVERT(VARCHAR(10), followupdate, 101),'') As [Follow Up]
FROM dbo.foxtrot a
) a
ORDER BY a.[Follow Up] DESC
答案 0 :(得分:4)
由于视图被视为子查询,因此排序会强制执行额外的工作。 SQL Server将自动对表或视图中的数据进行排序,以优化查找结果,这就是结果可以按随机顺序返回的原因。使用视图查询的任何过滤器和排序都会否定视图的排序子句。此外,根据您的视图所做的操作,SQL Server可能会选择将视图的内容提取到主查询中,以便可以在单个查询计划中进一步优化。
请记住,SQL Server本身并不关心它接收或提供结果的顺序。 TOP语句告诉SQL Server需要对记录进行排序,因为它会影响返回的结果。
从查询中选择结果时,您必须进行排序。
SELECT *
FROM MyView
ORDER BY [Follow Up] DESC;