在2005和2008中,如果将有序的记录插入临时表,则从临时表查看出来的记录是有序的(不使用Order by也是有序状态) 但从2012开始,即使插入的记录集是有序的,查看出来的结果变得无序了,需要依赖orderby来得到一个有序结果,感觉确实很郁闷
如果要求临时表的数据有序,
方法一则可以通过创建聚集索引来解决这个问题
DROP table #result
create table #result(
Id int null,
VideoName nvarchar(100) null,
CreatedOnUtc datetime NULL,
UpdatedOnUtc datetime NULL
)
CREATE CLUSTERED INDEX IDX_#tables_NAME ON #result(CreatedOnUtc desc);
insert into #result
SELECT
[Id] ,[SeoFilename] , [CreatedTime] , [UpdatedTime]
FROM [dbo].[Video] a WITH (NOLOCK) ORDER BY a.CreatedTime desc
SELECT * FROM #result
方法二:
可以使用ROW_NUMBER() OVER (ORDER BY w.CreatedTime desc ) RowID 这种方式进行排序
DROP table #result
create table #result(
RowID INT NULL,
Id int null,
VideoName nvarchar(100) null,
CreatedOnUtc datetime NULL,
UpdatedOnUtc datetime NULL
)
insert into #result
SELECT ROW_NUMBER() OVER (ORDER BY b.CreatedTime desc ) RowID,b.Id,b.SeoFilename,b.CreatedTime,b.UpdatedTime
FROM (
SELECT a.Id,a.SeoFilename,a.CreatedTime,a.UpdatedTime
FROM [dbo].[Video] a WITH (NOLOCK)) b
SELECT * FROM #result