开发者

order results by uniqueidentifer type column. is it reliable for my scenario?

I have a table that has id column of type uniqueidentifier. This column is PK too. This column has a default value of NewSequentialID() however most of the time its been populated through NewID() function. This table has another datetime type column too. I need to order results from this table by datetime column but if value of datetime is same that I need to get the data in same order as it was inserted in this table ( meaning the row that got inserted first should display first). If I o开发者_JAVA技巧rder my result by datetime first and then by Id column, will it give me what I need?

I know there could be better approaches ( like having some int type column with identity or something rather then relying on uniqueidentifier) but this thing is already in production and i need this sorting just for some repors.


No, it's not reliable. From the documentation:

Creates a GUID that is greater than any GUID previously generated by this function on a specified computer since Windows was started. After restarting Windows, the GUID can start again from a lower range, but is still globally unique.

It will probably work most of the time, but if your server has ever been restarted (and presumably it has if you are applying security updates) then you may run into problems. On the other hand, it's unlikely that there will be two rows inserted at the same time that the server was restarted so you may get away with it... but I'd strongly recommend changing your data model.


No. GUIDs won't necessarily be assigned in insertion order. The problem is that if your table isn't recording the insertion order then you can't expect to reproduce that order.


Timestamp value is the surest way to order the rows in the sequence in which they were inserted. You can test to see if more than one row has the same timestamp value:

            .... group by mytimestamp having count(*) > 1

I've never encountered that situation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜