sql - SQL Server - 如何从 datetime2 数据类型的毫秒中删除尾随零
问题描述
如何使用任何强制转换或转换函数从 datetime2 数据类型的毫秒中删除尾随零。
例如,我有这些数据:
2018-02-17 13:26:55.033000
2018-02-17 12:37:12.300000
2018-02-17 14:55:30.110000
我想将其更改为:
2018-02-17 13:26:55.033
2018-02-17 12:37:12.3
2018-02-17 14:55:30.11
提前致谢。
解决方案
-- Sample DDL/DML statements:
declare @tbl table (dt datetime2)
insert into @tbl values
('2018-02-17 13:26:55.033000'),
('2018-02-17 12:37:12.300000'),
('2018-02-17 14:55:30.110000')
-- Use this recursive CTE to trim trailing zeros.
-- The dt col is the original value, the rn col is a
-- recursive incrementor, and the vc col is the varchar
-- representation of the datetime2.
;with cte as
(
select dt, 1 as rn, cast(dt as varchar(100)) vc
from @tbl
union all
select dt, rn + 1, SUBSTRING(vc, 1, len(vc) - 1)
from cte
where SUBSTRING(reverse(vc), 1, 1) = '0'
)
select vc
from cte
where rn = (select max(rn) from cte c where dt = cte.dt)
vc
2018-02-17 14:55:30.11
2018-02-17 12:37:12.3
2018-02-17 13:26:55.033
推荐阅读
- python - 我的 Python 线性回归线不完整
- react-native - 如何在 ios 中的 react native webview 中捕获所有错误事件?
- java - ModelMapper 无法在 DeleteMapping 上将 java.util.list 转换为 java.util.list
- excel - Excel 2016 向 LAST ROW 插入新表行弄乱了公式
- swift - 创建 plist 并将其复制到文件夹 MacOS Swift
- c - 如何选择其中一个选项?
- php - 如何在 Laravel 5.6 的数据依赖选择输入中获取表数据以编辑表单?
- java - 错误:找不到符号(resultSetToTableModel)
- ubuntu - 运行“netplan apply”命令后,Netplan 和 Ubuntu 18.04 关闭我们的网络的问题
- javascript - 转置 d3.nest 结果的值