问题
I am trying to hash the datetime
column using HashBytes
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
but as it is non-deterministic, I get this error:
Computed column cannot be persisted because the column is non-deterministic.
I managed to get it done by not specifying the format as below
alter table dbo.PolicyEventsFromQueue
add HashKey AS hashbytes('MD5', cast( datestamp as varbinary)) persisted
But in SQL Server, when I see the results with the format and without format I am getting different results for the same field value:
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'
Result:
0xBE06A33FF10644A6D3B38EA134DDB97A
Second query:
select
hashbytes('MD5', cast('2016-06-30 12:19:35.257961' as varbinary))
Result:
0xBE06A33FF10644A6D3B38EA134DDB97A
Third query:
Select
convert(varchar(200), hashbytes('MD5', cast(DateStamp as varbinary)), 1)
From
Events
Where
DateStamp = '2016-06-30 12:19:35.257961'
Result:
0x3CB5C26B23EB4422515764686DFCAB82
Based on above research what I understood is SQL Server is converting datestamp to another format and then hashing.
But when I get the C# equivalent value for the same date ("2016-06-30 12:19:35.257961") using below function it is not matching with the hash value (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;
}
Can anybody hep to match date time format exactly as it taking in SQL Server and C# to make it work with HashBytes
.
Note: I need all date including miiliseconds. This question is followup to the below question. It might help you to understand the root problem.
Need C# equivalent for the below SQL HashBytes function
回答1:
I got the solution. I modified HashBytes logic as below to get the required datetime format and also on the C# side, I am using default encode.
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'
来源:https://stackoverflow.com/questions/38761149/hashbytes-computed-column-cannot-be-persisted-because-the-column-is-non-determin