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

拜拜、爱过 提交于 2019-12-08 15:06:58

问题


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?


回答1:


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)



回答2:


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



来源:https://stackoverflow.com/questions/19656213/different-casting-of-int-to-guid-in-c-sharp-and-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!