如何为时间列以 00:00:00 格式格式化时间值

时间:2020-12-23 22:38:43

标签: sql sql-server string time

如何为 SQL Server 中的 time 列以格式 00:00:00hh:mm:ss 格式化时间值?

我有一个场景,其中时间列中的值类似于

7:12:23
:1:23
:12:23
12:12:23
4:23

我想将它们格式化为

07:12:23
00:01:23
00:12:23
12:12:23
00:04:23

我尝试这样做,但最终无法实现 00:00:00 格式。谢谢。

2 个答案:

答案 0 :(得分:2)

您可以将 TimeFromParts()ParseName() 一起使用

示例

Declare @YourTable Table ([SomeCol] varchar(50))
Insert Into @YourTable Values 
 ('7:12:23')
,(':1:23')
,(':12:23')
,('12:12:23')
,('4:23')
 
Select SomeCol
      ,AsTime = TimeFromParts(
                              IsNull(parsename(S,3),0)
                             ,IsNull(parsename(S,2),0)
                             ,IsNull(parsename(S,1),0)
                             ,0
                             ,0
                             )
 From @YourTable
 Cross Apply ( values ( replace(SomeCol,':','.') ) ) B(S)

退货

SomeCol     AsTime
7:12:23     07:12:23
:1:23       00:01:23
:12:23      00:12:23
12:12:23    12:12:23
4:23        00:04:23

答案 1 :(得分:0)

Try_cast 和 try_convert 在这些情况下很方便,因为如果转换不成功,它们将返回 NULL 值。示例数据在第一个字符为 ':' 时失败。在这些情况下,此代码在前面加上“00”,然后转换成功。

declare @YourTable      table ([SomeCol] varchar(50));

insert into @YourTable values 
 ('7:12:23')
,(':1:23')
,(':12:23')
,('12:12:23')
,('4:23');

select try_cast(case when charindex(':', SomeCol)=1
                     then concat('00', SomeCol)
                     else SomeCol end as time) 
from @YourTable;

输出

(No column name)
07:12:23.0000000
00:01:23.0000000
00:12:23.0000000
12:12:23.0000000
04:23:00.0000000 

输出8个字符的格式化字符串

select convert(char(8), t.sc_time, 8) formatted_time
from @YourTable
     cross apply (values (try_cast(case when charindex(':', SomeCol)=1
                                        then concat('00', SomeCol)
                                        else SomeCol end as time))) t(sc_time);

输出

formatted_time
07:12:23
00:01:23
00:12:23
12:12:23
04:23:00
相关问题