[SQL tips] how to convert int-type data to HH: mm: SS time format

Source: Internet
Author: User

When it comes to some time data, it is not a specific date, for example, the length of a video, it is the number of seconds in the int type.
Exist in the database. We want it to be converted to the string form of HH: mm: SS for output display.

The general idea is to calculate the number of hours in the value, subtract this part, calculate the minute, calculate the second, and then splice the several parts.

In SQL, You Can skillfully use the dateadd date function for processing.

 

declare @totoaltime int
declare @tmpdate datetime
declare @hh varchar(2)
declare @mm varchar(2)
declare @ss varchar(2)
declare @datestr varchar(10)
set @totoaltime=101241

select @totoaltime
select @tmpdate=dateadd(second,@totoaltime,'')
select @tmpdate
select @hh=right('00'+cast(datepart(hh,@tmpdate) as varchar),2)
select @mm=right('00'+cast(datepart(n,@tmpdate) as varchar),2)
select @ss=right('00'+cast(datepart(s,@tmpdate) as varchar),2)
select @datestr=@hh+':'+@mm+':'+@ss
select @datestr

Encapsulate it into a custom function, and remove the hour part in less than one hour.

create function [dbo].[secondToDatestr](@second int)
returns varchar(10)
as
begin
declare @tmpdate datetime,@rtn varchar(10)
set @tmpdate=dateadd(second,@second,'')
set @rtn=right('00'+cast(datepart(hh,@tmpdate) as varchar),2)+':'
+right('00'+cast(datepart(n,@tmpdate) as varchar),2)+':'
+right('00'+cast(datepart(s,@tmpdate) as varchar),2)
if Charindex('00:',@rtn)=1
set @rtn=Stuff(@rtn,1,3,'')

return @rtn
end

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.