【问题标题】:Convert string to datetime - SQL将字符串转换为日期时间 - SQL
【发布时间】:2021-01-05 01:59:23
【问题描述】:

我有一个从 XML 解析的字符串,它代表日期时间。 字符串格式为:'20200915114000' - (YYYYMMDDhhmmss)

SQL Server 中是否有一个函数可以将此字符串转换或解析为日期时间,还是我应该手动拆分字符串并将其连接到日期时间?

【问题讨论】:

标签: sql-server sql-date-functions sql-convert


【解决方案1】:

如何做到这一点,分 3 步:

C:\> SQLCMD
1> select convert(datetime,'20200915114000' )
2> go
Msg 241, Level 16, State 1, Server ZES, Line 1
Conversion failed when converting date and/or time from character string.
1> select convert(datetime,'20200915 114000' )
2> go
Msg 242, Level 16, State 3, Server ZES, Line 1
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
1> select convert(datetime,'20200915 11:40:00' )
2> go

-----------------------
2020-09-15 11:40:00.000

(1 rows affected)
1>

结论您需要在字符串中添加一个空格和3个':'才能将'20200915114000'转换为'20200915 11:40:00'。在此之后,一个简单的 CONVERT 就可以解决问题。

【讨论】:

  • 谢谢,是的,我一直在收到“从字符串转换日期和/或时间时转换失败。”或其他错误现在可以了,我以为还有其他方法
【解决方案2】:

解决我的问题:

declare @sDate char(14), @sDateOK char(20)

set @sDate = '20200915114000'    
set @sDateOK = substring(@sDate,1,8) + ' ' + substring(@sDate,9,2) + ':' +  substring(@sDate,11,2) + ':' +  substring(@sDate,13,2)

select convert(datetime,@sDateOK ) as Date

【讨论】:

  • select convert(datetime,format(20200915114000,"00000000 00:00:00")) 也会这样做,这样甚至可以使用select convert(datetime,format(20200915114000,"0000-00-00 00:00:00")) 得到结果2020-09-15 11:40:00.000
猜你喜欢
  • 2019-04-12
  • 2021-06-26
  • 2017-05-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多