Ad
SQL Server - Cast Specific String Date Format To Date Datatype
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
Related Questions
- → I can't do a foreign key, constraint error
- → How to implement DbDongle::convertTimestamps as workaround of invalid timestamps with MySql strict
- → MySQL error "Foreign key constraint is incorrectly formed"
- → Eloquent Multitable query
- → "Laravel 5.1" add user and project with userId
- → Database backup with custom code in laravel 5 and get the data upto 10 rows from per table in database
- → Laravel 5.1 QueryException when trying to delete a project
- → Using Array in '->where()' for Laravel Query Building
- → Chaining "Count of Columns" of a Method to Single Query Builder
- → Laravel Eloquent Joining Strange query
- → convert time using mysql laravel 5
- → How to update a column after an expiration date in MySQL?
- → Foreign key constraint fails on existing key
Ad