I noticed when writing a sproc values inserted into a table variable were in a different order than insertion. Is there a way to disable this auto sorting without adding another column for sorting? Ideas that come to mind are an automatic index being created or some collation setting… any ideas?
Visit http://sqlfiddle.com/#!3/e1c06/13 to see exactly what I mean
declare @tmpTbl table (name varchar(100))
insert into @tmpTbl
select 'mark'
union
select 'frank'
union
select 'sharon'
union
select 'jason'
select * from @tmpTbl
If you wanted them ordered by the insert order then add an auto-incrementing field your table, and you can then include that in the ORDER BY when you SELECT the data.
SQL Server will otherwise not return your data in a particular order – it may seem to be returning it ‘sorted’ right now, but that may not be the case in the future.
By the way – the union query itself is actually returning the results ordered differently than they appear in your statement. This is likely the result of using UNION vs. UNION ALL, since union is distinct it likely implies a sort of some type. So, the result you’re getting actually IS the insert order.