Technical Article

Simple function to return time from datetime value

,

Since SQL Server stores time as a full datetime value, I use this script to return just the time part formatted as hh:mm:ss.

Usage:
Select mydb.dbo.udfHHMMSS(Getdate())

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[udfHHMMSS]') 
and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[udfHHMMSS]
GO

CREATE FUNCTION dbo.udfHHMMSS  (@dttm DATETIME)
RETURNS nvarchar(8)
AS
BEGIN
   Declare @udfHHMMSS nvarchar(8)
   SELECT @udfHHMMSS = RIGHT('0' + CAST(DATEPART(hh,@dttm) AS Varchar(2)), 2) + ':' + RIGHT('0' + CAST(DATEPART(mi,@dttm) AS Varchar(2)), 2) + ':' + RIGHT('0' + CAST(DATEPART(ss,@dttm) AS Varchar(2)), 2)
   RETURN(@udfHHMMSS)
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating