SQL SERVER临时表排序问题的解决方法

2022-07-25,,,,

在sql server 2005/2008中,如果将有序的记录插入临时表,则从临时表查询出来的记录是有序的(不依赖order by也是有序状态),但是从sql server 2012开始,即使插入的记录集有序,查询出来的结果变成无序了。需要依赖order by来或得到一个有序结果。例如下面例子:

select * into #tables from sys.tables order by name;
 
select * from #tables;

如上所示,sql server 2014则是无序状态,我很是奇怪怎么从sql server 2012就开始变成无序了,这对我们来说犹如一个黑盒子,只知道结果集出现了变化,但是不知道内部啥变化导致这个现象出现。records not sorted in the table when using order by clause to insert data into temp table 官方论坛对这个问题的描述如下:

如果有特殊的需要,要求临时表里面的数据有序,则可以通过创建聚集索引来解决这个问题。如下所示:

select * into #tables from sys.tables where 1= 0;
 
create clustered index idx_#tables_name on #tables(name);
 
insert into #tables select * from sys.tables order by name;
 
select * from #tables;


总结

到此这篇关于sql server临时表排序问题解决的文章就介绍到这了,更多相关sql server临时表排序问题内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

《SQL SERVER临时表排序问题的解决方法.doc》

下载本文的Word格式文档,以方便收藏与打印。