将 HHmmss 格式的 varchar(6) 转换为 sql 时间格式

Converting varchar(6) in HHmmss format to sql time format

如何将存储在DB中的东西转换为varchar(6)(例如,180000实际上是HHmmss的格式)到时间,我尝试了以下但不会工作

select convert(time,'180000')
select cast('180000' as time)

试试这个:

select cast((substring('180000',0,3)+':'+substring('180000',3,2)+':'+substring('180000',5,2)) as time)

另一种方法

DECLARE @t VARCHAR(6)='180000';

SELECT CAST(STUFF(STUFF(@t,5,0,':'),3,0,':') AS time)

感谢@SebtHU,他指出,在 09:15:0000:45:00 等时间,这不适用于前导零。您可以改用它:

SELECT CAST(STUFF(STUFF(RIGHT(CONCAT('000000',@t),6),5,0,':'),3,0,':') AS time);
select cast(format(180000, '00:00:00') as time), cast(format(131, '00:00:00') as time)