In SQL server how do I order table rows by insertion order if primary key is GUID?

这一生的挚爱 提交于 2019-12-10 15:35:30

问题


I've started using GUIDs over auto-increment integers for my primary keys.

However, during development I'm used to querying (from SQL management studio or visual studio) database in order to see what records my application just inserted, and I'm pissed off by the fact that I cannot order by primary key desc in order to see the most recent records.

Is there a way to accomplish tihs?


回答1:


You can't order a GUID column based on insertion order. You'll need to rely on another column.

My suggestion is to add a column called CreationMoment as a DateTime with a default value of GETDATE(). Theoretically you could have collisions (i.e. identical date / time of creation), so you'll have to decide if that data type is appropriate. In my experience it's never been an issue.




回答2:


You can't, you have to add new field bigint with auto increment and rely on, no need to make it key. no collisions and no size problem with bigint




回答3:


Both @Yuck and @Sameh have good answers, but I think a TIMESTAMP column is a better fit for your needs. It is guaranteed to be unique, and can be sorted using ORDER BY.

MSDN - timestamp (Transact-SQL)



来源:https://stackoverflow.com/questions/10501884/in-sql-server-how-do-i-order-table-rows-by-insertion-order-if-primary-key-is-gui

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