Can I use a SQL Server identity column to determine the inserted order of rows?

偶尔善良 提交于 2019-12-30 08:53:48

问题


I need to be able to determine the order which rows have been inserted into a table (there are no updates). Can I use an identity column to do this? I know that there may be gaps, but are the values guaranteed to be increasing by insertion order?


回答1:


Largely yes, as long as you don't ever reset it or insert rows with bulk copy, or use IDENTITY_INSERT. And of course assuming that you don't overflow the data-type (which could be impressive).




回答2:


Yes. Any gaps caused by deletions will not be reused




回答3:


As discussed by Marc, yes you can with provisos

What you should do however to definitively fix the problem is add a column

dteInserted datetime not null default getdate()

Then you just select ordered by this.

Myself I automatically add such a column onto any 'data' table in any database I'm designing. Storage is cheap nowadays and timestamping the insertion date on a row is always useful at some point.



来源:https://stackoverflow.com/questions/708607/can-i-use-a-sql-server-identity-column-to-determine-the-inserted-order-of-rows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!