SQL Server创建有序的#Temp表

时间:2012-07-31 20:31:30

标签: sql sql-server tsql

我尝试创建有序的#Temp表:

WITH Ordered AS (
SELECT ROW_NUMBER() OVER (ORDER BY [Quality] DESC) AS RowNumber, ImageID, Quality, Border, IsBest
  FROM [CatalogImages].[dbo].[Images] ORDER BY Quality)

SELECT *
  INTO #Temp
  FROM Ordered ;

 SELECT * FROM #Temp ;

但我收到错误:

  

Msg 1033,Level 15,State 1,Line 82
  ORDER BY子句无效   in views,内联函数,派生表,子查询和common   表表达式,除非还指定了TOP或FOR XML。

如何创建有序临时表?

1 个答案:

答案 0 :(得分:1)

错误是因为您试图在公用表表达式中执行Order By,这是不允许的。

根据您发布的内容,您的CTE似乎不是必需的。你可以这样做:

SELECT ROW_NUMBER() OVER (ORDER BY [Quality] DESC) AS RowNumber, ImageID, Quality, Border, IsBest 
INTO #Temp 
ORDER BY Quality; 

SELECT * 
FROM #Temp 
ORDER BY Quality; 

(这并不表示需要临时表,或者......)