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

后端 未结 6 1229
星月不相逢
星月不相逢 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条回答
  •  渐次进展
    2021-01-04 18:50

    First, thanks sgeddes for the explanation, it helped a lot. The thing about defining a table variable or creating a temp table is you have to define it, and if you are going to go through the work of defining it, you might as well do the insert the correct way:

    INSERT INTO #Result (col1, col2...)
    SELECT Col1, Col2... FROM #MyTable....
    

    In my case, the ORDER BY in the INSERT was dynamic so when I called "SELECT * FROM #Result", the ORDER BY was unknown. My solution was to add a ROW_NUMBER column that I could hardcode into the SELECT when I was getting the data. Yea, I still have to include an ORDER BY, but at least it's static. Here's what I did:

    --Insert
    SELECT ROW_NUMBER() OVER (ORDER BY T.SortOrder ASC) AS RowNum, T.*  
    INTO #Result 
    FROM (SELECT * FROM #MyTable ...) AS T;
    
    --Get data out
    SELECT * FROM #Result ORDER BY RowNum;
    

    Hope this helps.

提交回复
热议问题