Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert into Select does not insert the same data order correctly

Tags:

sql

sql-server

I used insert into command in SQL Server 2014, but does not insert as the same order of the data.

It shows the same number of rows but it not the same data order as you seen in the figures below.

The insert command is:

insert into [test].[dbo].[HöjdKortvågVänster] ([Höjd kortvåg vänster (null)]) select [Höjd kortvåg vänster (null)] from [test].[dbo].[test111]

Figure 1: Select command for the source table

enter image description here

Figure 2: Select command for the destination table

enter image description here

What can I do to solve this problem?

like image 267
Yamur Avatar asked Jul 30 '15 10:07

Yamur


1 Answers

SQL result sets are unordered, unless you have an order by. SQL tables are unordered.

However, SQL Server does provide at least one method to do what you want. If you use an order by in a table with an identity column and the select has an order by, then the identity is incremented appropriately.

So, one way of doing what you want is to have such as column in [HöjdKortvågVänster]:

id int not null identity(1, 1) primary key

insert into [test].[dbo].[HöjdKortvågVänster]([Höjd kortvåg vänster (null)]) 
    select [Höjd kortvåg vänster (null)]
    from [test].[dbo].[test111]
    order by <appropriate column here>;

And then when you query the table, remember the order by:

select *
from [test].[dbo].[HöjdKortvågVänster]
order by id;
like image 87
Gordon Linoff Avatar answered Nov 14 '22 23:11

Gordon Linoff