SQL 服务器 - 如何从 Nvarchar 类型转换日期时间类型?

SQL Server - How To Converting Datetime Type From Nvarchar Type?

我有两列nvarchar

示例数据为:

column1='20180402', column2='134259'

我的目标是通过组合这两列来创建一个 datetime 类型的列。

像这样:'2018-04-02 13:42:59.000'

我该怎么做?

请帮帮我?

您可以将两个字符串都转换为 datetime 值并将它们相加以获得组合的日期时间,或者组合这些字符串并转换结果。

请注意,需要添加两个 : 个字符才能正确解析:

select cast(d as datetime) + cast(stuff(stuff(t,5,0,':'),3,0,':') as datetime) as dt1
      ,cast(d + ' ' + stuff(stuff(t,5,0,':'),3,0,':') as datetime) as dt2
from (values('20180402','134259')) as v(d,t);

输出

+-------------------------+-------------------------+
|           dt1           |           dt2           |
+-------------------------+-------------------------+
| 2018-04-02 13:42:59.000 | 2018-04-02 13:42:59.000 |
+-------------------------+-------------------------+

您可以使用 DATETIMEFROMPARTS:

SELECT DATETIMEFROMPARTS(
    SUBSTRING(column1, 1, 4),
    SUBSTRING(column1, 5, 2),
    SUBSTRING(column1, 7, 2),
    SUBSTRING(column2, 1, 2),
    SUBSTRING(column2, 3, 2),
    SUBSTRING(column2, 5, 2),
    0
)
FROM (VALUES
    ('20180402', '134259')
) v(column1, column2)
declare @d varchar(50)='20180402',
        @t varchar(50)='134259'


select convert(varchar(50),convert(date,@d)) + ' '+ convert(varchar(50),dateadd(hour, (@T / 10000) % 100,
       dateadd(minute, (@T / 100) % 100,
       dateadd(second, (@T / 1) % 100,
       cast('00:00:00' as time(3))))) )