views:

527

answers:

2

We're storing some Guids 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 uniqueidentifier 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?

A: 

could this be a little or big endian problem?

Sven Hecht
+7  A: 

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.

Keith