Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different casting of int to guid in C# and SQL Server

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?

like image 905
Mladen Macanović Avatar asked Oct 29 '13 10:10

Mladen Macanović


1 Answers

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)
like image 148
Klark Avatar answered Oct 22 '22 23:10

Klark