How to convert custom string to Date in SQL Server

自古美人都是妖i 提交于 2021-02-10 06:14:38

问题


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

回答1:


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.




回答2:


Here is yet another approach to this. It is similar to what John Cappelletti posted.

Declare @S varchar(50)='2017092018'

Select dateadd(hour, convert(int, right(@s, 2)), left(@s, 8))



回答3:


Alternate approach using STUFF:

DECLARE @val VARCHAR(25) = '2017092018';

SELECT CONVERT(DATETIME,STUFF(@val, 9, 0, ' ') + ':00')

This adds a space before the hour, then adds :00 for the minute value.




回答4:


You could use DATETIMEFROMPARTS:

DECLARE @d NVARCHAR(10)='2017092018';

SELECT DATETIMEFROMPARTS(LEFT(@d,4),SUBSTRING(@d,5,2),SUBSTRING(@d,7,2),RIGHT(@d,2),0,0,0 ) ; 

Rextester Demo

EDIT:

Another option:

DECLARE @S varchar(10)='2017092018'
SELECT CAST(LEFT(@s, 8) AS DATETIME) + RIGHT(@s,2)/24.0;

Rextester Demo2



来源:https://stackoverflow.com/questions/46324500/how-to-convert-custom-string-to-date-in-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!