Split Time
A scalar function that returns the time portion of a datetime as a string.
Sometimes you have a datetime column but only care about the time portion as text. This tiny scalar function converts the value to style 100 (mon dyy hh:mmAM) and returns everything after the space - just the time.
Example: SELECT dbo.SplitTime('2024-03-15 14:30:45') -- returns 02:30PM
CREATE FUNCTION SplitTime
(
@Date DateTime
)
RETURNS VarChar(50)
AS
BEGIN
DECLARE @VcDate VarChar(50)
SET @VcDate = Convert(VarChar, @Date, 100)
RETURN LTrim(SubString(@VcDate, (len(@VcDate) - CharIndex(' ', Reverse(@VcDate))) + 1, 100))
END
GO