I am looking to convert a string like this: 20160520191959550
- that is actually date-time for 2016-05-20 19:19:59
.
I tried using CAST as datetime
in a SQL statement, but got this error:
Conversion failed when converting date and/or time from character string.
Here is the SQL:
Select Cast(vbon.DATE_INS As datetime) As DINS
From vbon
I routinely use CAST
on date strings without delimiters and am looking for a similar solution. Is there a simple way to get the job done without reverting to LEFT
, RIGHT
and SUBSTRING
?
You can try this:
Ref: Convert DateTime to yyyyMMddHHmm in T-SQL
In SQL Server 2012 and later, you can use
DATETIMEFROMPARTS
:In earlier versions, one method is to build a ISO 8601 formatted string and use
CAST
orCONVERT
:I suggest you to create function:
You can call it like:
Output:
If you pass it wrong value you will get
NULL
I think convert would work for you. I can't test right now but I have done what you are looking for with dates. Here is a good article: http://www.sqlusa.com/bestpractices/datetimeconversion/
Addtional variant to already posted: