Insert disordered in temporary table

1

When I do the select only returns the query as I want.

Select Distinct NombreCliente,OELMDT,OEQLVA,CodigoCliente,TLLINO,TLTX60
From #Templino,#Tempcliente
Where (CodigoCliente=CONCAT(RTRIM(#Templino.OEQLVA),'0000'))OR(CodigoCliente = CONCAT(RTRIM(#Templino.OEQLVA),'ZZZZ'))
Order by CodigoCliente, TLLINO asc;

The problem is that when I try to save these results in a temporary table, the order is passed, I do not know where ...

create table #Tempclientelino
(
    NombreCliente varchar(255), 
    OELMDT varchar(255),
    OEQLVA varchar(255),
    CodigoCliente varchar(255),
    TLLINO varchar(255),
    TLTX60 varchar(255) 
)

Insert Into #Tempclientelino
Select Distinct NombreCliente,OELMDT,OEQLVA,CodigoCliente,TLLINO,TLTX60
From #Templino,#Tempcliente
Where (CodigoCliente=CONCAT(RTRIM(#Templino.OEQLVA),'0000'))OR(CodigoCliente = CONCAT(RTRIM(#Templino.OEQLVA),'ZZZZ'))
Order by CodigoCliente, TLLINO asc;
    
asked by GDP 01.08.2017 в 10:36
source

2 answers

1

SQL Server does not guarantee any order unless we use the ORDER BY clause, it does not matter if the order is given when inserting, nor, if we also manage to physically insert the records with said order, we have no guarantee that this order will be respected when making a SELECT unless we use a ORDER BY . Assuming that the order of insertion is the "natural order" that uses a SELECT with temporary tables may be due to a behavior in one of the previous versions, I'm not sure which, but I do remember serious problems like the one you mention. The solution that we find because many times in the temporary we do not keep the fields that we want to order: always use a field Order INT IDENTITY , insert with the desired order and then make a ORDER BY Orden

    
answered by 01.08.2017 / 17:17
source
3

The sql server tables, from any relational database, do not have an associated ordering and it is necessary to specify the order by clause to obtain a certain sort.

    
answered by 01.08.2017 в 10:50