Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert custom string to Date in SQL Server

How to convert yyyyMMddhh (2017092018) string to Date in SQL Server 2012?

Is it possible to do without using T-SQL to put the sentence into the INSERT clause?

INSERT INTO [dbo].[Table](SomeColumn) 
VALUES (CONVERT(DATETIME, '2017092018', 'yyyyMMddhh'));
like image 828
Evgeny Bychkov Avatar asked May 07 '26 14:05

Evgeny Bychkov


1 Answers

Example

Declare @S varchar(50)='2017092018'

Select convert(datetime,left(@S,8)) + convert(datetime,right(@S,2)+':00')

Returns

2017-09-20 18:00:00.000

If 2012+, I would suggest try_convert() just in case you have some unexpected values.

like image 51
John Cappelletti Avatar answered May 09 '26 04:05

John Cappelletti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!