SELECT * INTO retains ORDER BY in SQL Server 2008 but not 2012

后端 未结 6 1211
星月不相逢
星月不相逢 2021-01-04 18:34

Execute the following SQL in 2008 and 2012. When executed in 2008, the returned result is in its correct sort order. In 2012, the sortorder is not retained.

Is this

6条回答
  •  旧时难觅i
    2021-01-04 18:44

    How can you tell what the order is inside a table by using select * from #result? There is no guarantee as to the order in a select query.

    However, the results are different on SQL Fiddle. If you want to guarantee that the results are the same, then add a primary key. Then the insertion order is guaranteed:

    CREATE TABLE MyTable(Name VARCHAR(50), SortOrder INT)
    INSERT INTO MyTable SELECT 'b', 2 UNION ALL SELECT 'c', 3 UNION ALL SELECT 'a', 1 UNION ALL SELECT 'e', 5 UNION ALL SELECT 'd', 4
    
    
    select top 0 * into result from MyTable;
    
    alter table Result add id int identity(1, 1) primary key;
    
    insert into Result(name, sortorder)
        SELECT * FROM MyTable
        ORDER BY SortOrder;
    

    I still abhor doing select * from Result after this. But yes, it does return them in the correct order in both SQL Server 2008 and 2012. Not only that, but because SQL Server guarantees that primary keys are inserted in the proper order, the records are even guaranteed to be in the correct order in this case.

    BUT . . . just because the records are in a particular order on the pages doesn't mean they will be retrieved in that order with no order by clause.

提交回复
热议问题