Ad

SQL Server - Cast Specific String Date Format To Date Datatype

- 1 answer

I am trying to insert data into a DATE column in Microsoft SQL using the code below:

INSERT INTO sde.AMD_NDVI_CAT (OBJECTID, Name, ImageDate) 
VALUES (6199,'VI_{960D55A4-EEFD-45DD-80FD-81B5113C43D5}_20220122T090159', CAST('20220122T090159' AS DATE))

What I get is:

Conversion failed when converting date and/or time from character string.

The data to be inserted into ImageDate column has the format YYYYMMDDTHHMMSS. I did not find this format on the Microsoft webpage (https://docs.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-ver15). How can I convert it to date in order to be inserted into the table?

Thanks!

Ad

Answer

Since date suggests you don't care about time:

SELECT CONVERT(date, LEFT('20220122T090159', 8));

If you need time too, it gets quite ugly.

DECLARE @funny_string char(15) = '20220122T090159';

SELECT TRY_CONVERT(datetime, 
  LEFT(@funny_string, 8) + ' ' 
  + STUFF(STUFF(RIGHT(@funny_string, 6), 3, 0, ':'),6, 0, ':'));
Ad
source: stackoverflow.com
Ad