Is there a way to use SELECT...INTO with an ORDER BY clause and ensure the ordering is done before the INTO?I have a SELECT...INTO with an IDENTITY(int,1,1) as RowNum. It seems that the ordering beging done after the temp table is populated and the the order of the IDENTITY is based on the clustered index used rather than the ORDER BY clasue.Consider ...--create intotest with clustered index on acreate table intotest ( a int identity(1,1) not null primary key, b int not null)--populate with random numbersinsert into intotest (b)select n from numbers order by newid()go--create temp table ordered by bselect identity(int,-1,-1) as RowNum, binto #tempfrom intotestorder by b--what happened to my ordering?select top 10 * from #temp order by rownumgo--try againdrop table intotestdrop table #tempgo--create intotest, this time with the clustered index on bcreate table intotest ( a int identity(1,1) not null, b int not null, constraint pk_intotest primary key nonclustered (a))create clustered index cx_intotest on intotest(b)insert into intotest (b)select n from numbers order by newid()goselect identity(int,-1,-1) as RowNum, binto #tempfrom intotestorder by b--now that's right ...select top 10 * from #temp order by rownumgo
Any ideas how I could rewrite the first select...into so the ordering is correct?Jay White{0}