c# - C# 和 SQL Server 中 int 到 guid 的不同转换

标签 c# sql-server int guid uniqueidentifier

在 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

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

最佳答案

发生这种情况是因为 sql server 和 .net 以不同的格式存储 int。 这将达到目的:

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

关于c# - C# 和 SQL Server 中 int 到 guid 的不同转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19656213/

相关文章:

c# - c#中的using结构怎么样

c# - 调试 NavigationService.GoBack() 问题的最佳方法?

c# - 在 SqlGeometry 和 DbGeometry 之间转换

sql - 将字符串中的 int 转换为 T-SQL 中的整数

c - 在 C 中,我的函数输出总是 0.000000。是不是因为两个输入都是int?

c# - 如何检查字符串值是否在枚举列表中?

c# - 如何设置两个连接字符串MySqlCommand对象参数?

sql - 从满足两个条件的同一列中选择数据

C 编程使用静态函数将华氏温度转换为摄氏度误差

c++ - 整数比较不正确或不比较