1

I try to create ordered #Temp table:

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 ;

but I get error:

Msg 1033, Level 15, State 1, Line 82
The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP or FOR XML is also specified.

How to create ordered temp table?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
testCoder
  • 7,155
  • 13
  • 56
  • 75
  • 2
    Google the message. This is a well-known error. – usr Jul 31 '12 at 20:36
  • Oh, thanks, i was found solution http://stackoverflow.com/questions/985921/sql-error-with-order-by-in-subquery – testCoder Jul 31 '12 at 20:39
  • 3
    As a side-note: you cannot have an **ordered** table - temporary or not. When you select from a table in SQL, unless you **explicitly specify** an `ORDER BY` - there **is no guaranteed order** – marc_s Jul 31 '12 at 20:48

1 Answers1

1

The Error is because you're trying to do an Order By inside a Common Table Expression, which is not allowed.

Just from what you've posted, it does not appear that your CTE is required. You could just do this :

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; 

(which doesn't suggest that a temp table is required, either...)

ShaneBlake
  • 11,056
  • 2
  • 26
  • 43