14
votes

When converting int to guid in C# and SQL Server I get different values.

In C# I use this method

public static Guid Int2Guid( int value )
{
    byte[] bytes = new byte[16];
    BitConverter.GetBytes( value ).CopyTo( bytes, 0 );
    return new Guid( bytes );
}

Console.Write( Int2Guid( 1000 ).ToString() );
// writes 000003e8-0000-0000-0000-000000000000

In SQL Server I use

select cast(cast(1000 as varbinary(16)) as uniqueidentifier)
-- writes E8030000-0000-0000-0000-000000000000

Why would they behave differently?

2

2 Answers

18
votes

This happens because sql server and .net store int in different format. This will do the trick:

select cast(CONVERT(BINARY(16), REVERSE(CONVERT(BINARY(16), 1000))) as uniqueidentifier)
3
votes

The bytes in each group in SQL Server are "reversed" for the first 8 bytes in each group. Check the documentation for uniqueidentifier http://technet.microsoft.com/en-us/library/aa223933(v=sql.80).aspx

It states that there are 2 ways of providing the value - pay attention to the order of bytes:

Character string format '6F9619FF-8B86-D011-B42D-00C04FC964FF'

Binary format 0xff19966f868b11d0b42d00c04fc964ff