如何在 SQL Server 中将自定义字符串转换为日期

2021-09-10 00:00:00 sql tsql sql-server

如何在 SQL Server 2012 中将 yyyyMMddhh (2017092018) 字符串转换为 Date?

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

是否可以不使用T-SQL将句子放入INSERT子句中?

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

推荐答案

示例

Declare @S varchar(50)='2017092018'

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

退货

2017-09-20 18:00:00.000

如果是 2012+,我会建议 try_convert() 以防万一你有一些意外的值.

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

相关文章