This question already has answers here:
Convert integer data type to time (2 answers)
Converting numeric(17,9) into a datetime (3 answers)
Closed 5 days ago.
I want to convert start_date numeric(16) to datetime
for example:
2023032012121201 to Datetime
I tried this
SELECT CONVERT(datetime, SUBSTRING(CAST(start_date AS varchar(16)), 1, 8) + ' ' +
STUFF(STUFF(STUFF(RIGHT('0000000000'
+ CAST(start_date AS varchar(16)), 10), 3, 0, ':'), 6, 0, ':'), 9, 0, '.'))
FROM table
but it gives Conversion failed when converting date and/or time from character string error
Output should be: 2023-03-20T12:12:12.01
2条答案
按热度按时间b4lqfgs41#
If the value is a
numeric(16,0)
(or avarchar(16)
), then you can inject the needed characters ( `` ,:
and.
) into the needed positions and thenTRY_CONVERT
that to adatetime2(2)
. This turns the value into the formatyyyyMMdd hh:mm:ss.nn
which is an unambiguous date and time format in SQL Server:I use
TRY_CONVERT
because you might have bad data; storing date and time values in anything other than a date and time data type throws validation out the window. As such any such values will returnNULL
instead. Likely you will also want to find and correct such values before you fix your design and change the data type to a date and time data type (datetime2(2)
seems the right choice here, and why I used it).2izufjch2#
Another possibility is
fiddle