【问题标题】:Hashbytes Computed column cannot be persisted because the column is non-deterministicHashbytes 计算的列不能被持久化,因为该列是不确定的
【发布时间】:2016-08-04 07:33:40
【问题描述】:

我正在尝试使用 HashBytes 散列 datetime

alter table dbo.Events 
add HashKey AS hashbytes('MD5', cast(convert(varchar(200), format(datestamp,'yyyy-MM-dd HH:mm:ss.ffffff')) as  varbinary)) persisted

但由于它是非确定性的,我收到此错误:

计算的列无法持久化,因为该列是不确定的。

我设法通过没有指定如下格式来完成它

alter table dbo.PolicyEventsFromQueue 
add HashKey AS hashbytes('MD5', cast( datestamp as  varbinary)) persisted

但是在 SQL Server 中,当我看到有格式和没有格式的结果时,我会得到相同字段值的不同结果:

Select 
    convert(varchar(200), hashbytes('MD5', cast(convert(varchar(200), format(datestamp, 'yyyy-MM-dd HH:mm:ss.ffffff')) as varbinary)), 1)  
From 
    Events
Where 
    DateStamp ='2016-06-30 12:19:35.257961'

结果:

0xBE06A33FF10644A6D3B38EA134DDB97A

第二次查询:

select 
    hashbytes('MD5', cast('2016-06-30 12:19:35.257961' as varbinary))

结果:

0xBE06A33FF10644A6D3B38EA134DDB97A

第三次查询:

Select 
    convert(varchar(200), hashbytes('MD5', cast(DateStamp as varbinary)), 1)  
From 
    Events 
Where 
    DateStamp = '2016-06-30 12:19:35.257961'

结果:

0x3CB5C26B23EB4422515764686DFCAB82

根据上述研究,我了解到 SQL Server 正在将日期戳转换为另一种格式,然后进行散列。

但是当我使用以下函数获得同一日期的 C# 等效值(“2016-06-30 12:19:35.257961”)时,它与哈希值不匹配(0x3CB5C26B23EB4422515764686DFCAB82)。

public static byte[] GetMD5Hash(string input)
{
        System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
        byte[] bs = System.Text.Encoding.Unicode.GetBytes(input);

        bs = x.ComputeHash(bs);

        return bs;
}

任何人都可以完全匹配日期时间格式,就像它在 SQL Server 和 C# 中所采用的那样,使其与HashBytes 一起工作。

注意:我需要所有日期,包括毫秒。这个问题是对以下问题的跟进。它可能会帮助您了解根本问题。

Need C# equivalent for the below SQL HashBytes function

【问题讨论】:

  • 我得到了解决方案。我修改了 HashBytes 逻辑如下以获得所需的日期时间格式,并且在 C# 端我使用默认编码。 Select hashbytes('MD5', convert(varchar(200),(CONVERT(varchar(10),datestamp,126)+' '+CONVERT(VARCHAR(24),datestamp,114)),2)) from Events Where DateStamp ='2016-06-30 12:19:35.257961'
  • 你应该把你的答案作为这个问题的答案,并将其标记为正确的解决方案。

标签: c# sql-server hashbytes


【解决方案1】:

我得到了解决方案。我修改了 HashBytes 逻辑如下以获得所需的日期时间格式,并且在 C# 端,我使用默认编码。

Select hashbytes('MD5', convert(varchar(200),(CONVERT(varchar(10),datestamp,126)+' '+CONVERT(VARCHAR(24),datestamp,114)),2))
from Events
Where DateStamp ='2016-06-30 12:19:35.257961'

【讨论】:

    猜你喜欢
    • 2019-12-21
    • 1970-01-01
    • 2010-12-16
    • 2012-12-16
    • 2010-10-29
    • 1970-01-01
    • 1970-01-01
    • 2010-09-18
    相关资源
    最近更新 更多