Home > Enterprise >  SQL Server - Cast specific string date format to date datatype
SQL Server - Cast specific string date format to date datatype

Time:02-18

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!

CodePudding user response:

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, ':'));

CodePudding user response:

If you need to capture both date and time, then we can use TRY_CONVERT along with a bit of string manipulation:

SELECT TRY_CONVERT(datetime,
                   LEFT(ts, 8)   ' '   SUBSTRING(ts, 10, 2)   ':'  
                   SUBSTRING(ts, 12, 2)   ':'   SUBSTRING(ts, 14, 2))
FROM t;

Demo

Note that here I am building the timestamp 20220122 09:01:59 from the input string 20220122T090159.

  • Related