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?
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.
.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.
Answer author Keith
Tickanswer.com is providing the only single recommended solution of the question Why does Guid.ToString() reverse the byte order? under the categories i.e .net , sql-server , . Our team of experts filter the best solution for you.