richardtallent / RT.Comb

Creating sequential GUIDs in C# for MSSQL or PostgreSql
203 stars 35 forks source link

T-SQL in README for extracting DateTime from COMB needs some tweaks #2

Closed ventaur closed 8 years ago

ventaur commented 8 years ago

The T-SQL in the README for extracting the DateTime value from the COMB is off (at least for the SQL Server 2014).

Currently, this is in the README: CAST(SUBSTRING(CAST(0 AS binary(2)) + CAST(value AS binary(16), 10, 6) AS datetime)

The Substring function's index is 1-based instead of 0-based. Additionally, I think the 0-fill at the beginning needs to be prepended separately from the Substring of the value. Here is the revised version: CAST(CAST(0 AS binary(2)) + SUBSTRING(CAST(value AS binary(16)), 11, 6) AS datetime)

Additionally, here is a quick script to verify everything in SQL Server.

-- Quick verification of extracting date/time from COMB GUID value.
DECLARE @Today AS datetime
DECLARE @ToCombGuid AS uniqueidentifier
DECLARE @FromCombGuid AS datetime
DECLARE @IsMatch AS bit

SET @Today = GETUTCDATE()
SET @ToCombGuid = CAST(CAST(NEWID() AS binary(10)) + CAST(@Today AS binary(6)) AS uniqueidentifier)
SET @FromCombGuid = CAST(CAST(0 AS binary(2)) + SUBSTRING(CAST(@ToCombGuid AS binary(16)), 11, 6) AS datetime)
SET @IsMatch = IIF(@Today = @FromCombGuid, 1, 0)

select @Today AS Today, @ToCombGuid AS ToCombGuid, @FromCombGuid AS FromCombGuid, @IsMatch

This library is a great idea! I've got code like it scattered around as well.

richardtallent commented 8 years ago

Thanks! Yes, I must've written that part pretty late at night and then forgot to check it. Fixed. :)

ventaur commented 8 years ago

Been there! Glad to help.