sql-server-2012 - 日期和时间的连接并格式化
问题描述
我有一个以下数据集。
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”
解决方案
正如@Larnu 所说,您“应该将格式留给表示层”并将基本数据留在数据库中。但是,如果您出于某种原因真的必须这样做,请尝试:
select CONCAT(cast(filedate as varchar(8)), '-', FORMAT(filedate_time,'hh:mm tt'))
from #table
推荐阅读
- javascript - 附加带有精灵图像的文本并使文本能够与精灵图像进行补间
- php - 从 HTML 表单使用 PHP 编辑 SQL 表
- indexing - Julia MetaCollection:实现集合的集合
- javascript - 使页脚停留在页面底部而不被剪切
- arrays - 如何在groovy中迭代数组参数
- angular - Angular AOT forRoot 有条件地定义提供者
- android - 如何在颤振中创建 SharedPreferences 的 Singleton 类
- android - 对象引用未设置为 Droid.MainActivity.OnCreate(Android.OS.Bundle 捆绑包)中的对象实例 - Sdk 和用户程序集
- php - 回到我几个月没碰过的 Laravel 项目,收到“compact(): Undefined variable: operator”错误
- javascript - 基于两个条件(重复的mac地址和使用条件小于或大于)从JavaScript中的对象数组中删除对象