首页 > 解决方案 > 日期和时间的连接并格式化

问题描述

我有一个以下数据集。

Create table #table
(
    id int,
    filedate int,
    filedate_time datetime2
)

Insert into #table
select 1,20190801,'8/1/2019 1:33:25 PM'
union
select 2,20190802,'8/2/2019 2:40:25 PM'
union
select 3,20190803,'8/3/2019 1:33:25 PM'

select 
    cast(filedate_time as time) as time_only,
    cast(filedate as varchar(8)) as filedate,
    concat(cast(filedate as varchar(8)), ' ', cast(filedate_time as time)) as concatfield
from 
    #table

我想连接来自 filedate_time 的时间和来自 filedate 的日期,并将它们格式化为 yyyyMMdd-hh:mm:ss.fff。

我不能使用 FORMAT 函数,因为它说第一个参数不应该是 varchar。我无法将 concat 字段转换为 datetime2。它给了我一个错误,说不能将字符串转换为日期时间。我无法更改源数据类型。

谁能帮我获得正确的格式?

我希望 concatfield 为“20190805-3:50:55 PM”

标签: sql-server-2012

解决方案


正如@Larnu 所说,您“应该将格式留给表示层”并将基本数据留在数据库中。但是,如果您出于某种原因真的必须这样做,请尝试:

select CONCAT(cast(filedate as varchar(8)), '-', FORMAT(filedate_time,'hh:mm tt'))
from #table

推荐阅读