C#和SQL Server中int转guid的不同转换方式

16

在将int转换为guid时,我在C#和SQL Server中得到了不同的值。

在C#中,我使用以下方法:

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

在SQL Server中我使用

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

他们为什么会表现不同呢?

2个回答

22

发生这种情况是因为SQL Server和.NET在存储int时采用了不同的格式。 以下代码可解决此问题:

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

3
在SQL Server中,每个组中的前8个字节的字节是“反向”的。请查看 uniqueidentifier 的文档http://technet.microsoft.com/en-us/library/aa223933(v=sql.80).aspx,其中指出提供值的两种方式,请注意字节的顺序:
字符字符串格式 '6F9619FF-8B86-D011-B42D-00C04FC964FF'
二进制格式 0xff19966f868b11d0b42d00c04fc964ff

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接