It’s not clear what you mean by
maintain a sequence of elements in a temporary table
but if you want to get the result ordered by eserial , you need to add ORDER BY eserial to your query. Without ORDER BY resulting rows can be returned in any order. This applies to any method you choose.
So, taking your last request as a basis, it will look like this:
Select lst.eserial ,lst.refdate ,app.CREATEDDATETIME From
To make it work quickly and efficiently, add the TableSource index to (ESERIAL, CREATEDDATETIME) . The order of the columns in the index is important.
It is also important to know if there are any other columns that you use in the OUTER APPLY query and how you use them. You mentioned the AREAID column in the first version in the question, but not in the last version. If you have more columns, then clearly show how you are going to use them, because the correct index depends on it. An index on (ESERIAL, CREATEDDATETIME) enough for the query I wrote above, but if you have more columns, you may need a different index.
It will also help the optimizer if you defined your temporary table using PRIMARY KEY :
Create Table
The primary key will create a unique clustered index.
Another important point. What is the type and sorting of the eserial and CREATEDDATETIME in the main TableSource ? Verify that the types and collation of the columns in the temp table matches the main table, TableSource . If the type is different ( varchar vs. nvarchar or datetime vs. date ) or the sorting is different from the index, it cannot be used => it will be slow.
Edit
You use the phrase “the same sequence as the temporary table” several times in the question, but it’s not entirely clear what you mean by that. Your sample data does not help to eliminate ambiguity. The eserial column eserial also adds to the confusion. I see two possible values:
- Return rows from temp table sorted by values in the
eserial column. - Returns the rows from the temp table in the same order in which they were inserted.
My initial answer implies (1): it returns the rows from the temp table, sorted by the values in the eserial column.
If you want to keep the order of the rows when they were inserted into the table, you need to explicitly remember this order. The easiest way is to add the IDENTITY column to the temp table and then arrange that column. Like this:
Create Table
And in the last query use ORDER BY lst.ID