在 C# 和 SQL Server 中将 int 转换为 guid

本文关键字:int 转换 guid 中将 Server SQL | 更新日期: 2023-09-27 18:37:21

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

在 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

为什么他们的行为会有所不同?

在 C# 和 SQL Server 中将 int 转换为 guid

发生这种情况是因为 sql server 和 .net 以不同的格式存储 int。这将解决问题:

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

SQL Server 中每个组中的字节对于每个组中的前 8 个字节进行"反转"。查看 uniqueidentifier http://technet.microsoft.com/en-us/library/aa223933(v=sql.80) 的文档.aspx

它指出有 2 种提供值的方法 - 注意字节的顺序:

字符串格式 '6F9619FF-8B86-D011-B42D-00C04FC964FF'

二进制格式 0xff19966f868b11d0b42d00c04fc964ff