Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Guid.ToString() reverse the byte order?

We're storing some Guid's in a MS SQL database. There's some legacy code that does Guid.ToString() and then passes them in to a varchar(64) and there's some newer code that passes them in using a unique identifier parameter. When you look at the results using MS SQL Management studio they look different. The byte order of the first three blocks is reversed but the last one remains the same. Why?

like image 378
d4nt Avatar asked Aug 20 '08 09:08

d4nt


1 Answers

Uniqueidentifier fields in Sql server can be indexed, and so are 'backwards'.

Guids can be generated from both machine specific info and 'event-time' information.

The default Guid in .Net is random, but you can get sequential Guids from it with an extern call:

[DllImport( "rpcrt4.dll", SetLastError = true )]
static extern int UuidCreateSequential( out Guid guid );

This will get you Guids based on your MAC address (MSDN docs) that are sequential.

If you .ToString() these sequential guids then you will see the first part of the string varies, while the rest stays constant.

This makes equality checks between Guids quicker (as the differences will be at the start) and improves the variation for truncated ones.

For searching columns SqlServer builds indexes in a similar way to a telephone directory or dictionary. It is much quicker to search for words starting with "Over*" than it would be to find ones ending in "*flow".

This means that for Sql server any sequential Guids need to be stored with the repeating value first, so it stores them back to front.

like image 70
Keith Avatar answered Oct 31 '22 23:10

Keith