2

I understand from various sources on the internet that the following sql:

insert into mainTable(status)
output inserted.mainid into tmpTable(TARGET_ID)
select '0' from impTable
order by impid asc;

doesn't guarantee that the rows will be inserted in the mainTable in the order specified by the 'order by' in the select statement, although the values in the mainTable identity column (mainid) will be in the correct sequence.

My question is how this affects the inserted.mainid that is output into the tmpTable. Will they be added to the tmpTable in the order rows are inserted in the mainTable or will they folllow the sequence of the generated mainid identity values?

Nevermind the usefulness of the SQL, it's a technical question.

EDIT: Fixed the column missmatch in the SQL example

4

3 回答 3

2

As you state in your comment mainid is an IDENTITY column, its value will increase monotonically but, since the value you are inserting are not from impTable I don't see how this matters.

Each new mainId will get inserted into tmpTable. The data will be stored in the order of the clutsered index of tmpTable, if tmpTable has no clustered index, then the order is undefined. This doesn't matter either way, except for performance reasons. When you select data from tmpTable the order of results wil be undefined unless you specify an ORDER BY.

于 2013-03-08T10:48:13.617 回答
1

It does not matter what order rows are stored in the table because you can't observe that order. When selecting without order by the order is undefined and does not necessarily conform to stored order. The stored order is meaningless for that reason.

There is no way to say "give me all rows in stored order". All you can say is "return them in any order" or "return them in this exact order".

于 2013-03-08T10:59:09.137 回答
0

There is no way to know the order.

If you look at this page from MSDN (http://msdn.microsoft.com/en-us/library/ms177564.aspx) you will find the following statement:

"There is no guarantee that the order in which the changes are applied to the table and the order in which the rows are inserted into the output table or table variable will correspond."

于 2013-03-11T07:22:59.943 回答