1

Supposing you have the following atrocious data structure in your SQL Server database to hold Date Times.

  • Year (int)
  • Month (int)
  • Day (int)
  • Hour (int)
  • Minute (int)
  • Second and Millisecond (float)

And you need to keep it but create a computed DATETIME2 column based upon it, and in your data in one of your fields overflows its real capacity (e.g. "Second and Millsecond" holds 60 or greater) and you want to convert these fields into a DATETIME2; how can you do this so that any overflowing values cascade into a higher date/time component? For example, the following invalid DateTime data would convert as follows:

  • 2018-01-01 10:00:60.111 ► 2018-01-01 10:01:00.111
  • 2018-12-31 23:59:61.123 ► 2019-01-01 00:00:01.123
  • 2018-01-01 10:00:120.000 ► 2018-01-01 10:02:00.000

With my particular problem the data I've seen is only overflowing on seconds and seconds should only be 2 digits so they won't overflow by more than 1 minute, so a solution just for this would suffice for the immediate data. However, I don't like that we've got to keep these int and float fields in our database to hold Date Times and would ultimately like a more bullet-proof means of handling any kind of overflow (and underflow too for completeness).

I don't mind whether the component fields are re-assigned to to make them valid for a DATETIME2 or the new DATETIME2 computed column is assigned the converted result directly and the bad data remains in the component fields; just so long as the computed column for DATETIME2 can be persisted.

1
  • 1
    You could use check constraints to ensure that invalid data can't be stored in the table or triggers to validate and normalize the data. A persisted computed column could be used to make the DateTime2 value available without having to assemble it every time it is needed, and it can be indexed.
    – HABO
    Apr 26, 2019 at 20:03

1 Answer 1

1

Basically, my idea is:

1, Use 0 as the Seconds firstly,

2, add Seconds from SnM (Seconds and Milliseconds)

3, add Milliseconds from SnM.

Be careful of data type conversion issue...

Try this:

select 
dateadd(millisecond, cast(reverse(substring(reverse(cast(cast (SnM as decimal(10,3)) as varchar(50))),1,3)) as int),
dateadd(second, cast(substring(cast(cast (SnM as decimal(10,3)) as varchar(50)),1,charindex('.',cast(cast (SnM as decimal(10,3)) as varchar(50)))-1) as int), 
cast(concat(year,'-',month,'-',day,' ',hour,':',minute,':00') as datetime2))) as newdate
from test

Test Result:

SQL<>Fiddle

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.