User Defined Function (UDF) to Convert Speed between Km/h and m/s in SQL Server

To create a User Defined Function (UDF) that converts speed from Kilometers per Hour to Meters per Second, that uses decimal(10,3) data type with precision 10 and scale 3 for input and output speed values, use the following command:

CREATE FUNCTION [dbo].[ufn_kmph2mps] (@kmph decimal(10,3))
RETURNS decimal(10,3)
AS
BEGIN
RETURN (@kmph / 3.6)
END

To use this user-defined function (for example to convert 120 Kilometers per Hour to Meters per Second):

SELECT dbo.ufn_kmph2mps (120)

ufn_kmph2mps

To create a User Defined Function (UDF) that converts speed from Meters per Second to Kilometers per Hour, that uses decimal(10,3) data type with precision 10 and scale 3 for input and output speed values, use the following command:

CREATE FUNCTION [dbo].[ufn_mps2kmph] (@mps decimal(10,3))
RETURNS decimal(10,3)
AS
BEGIN
RETURN (@mps * 3.6)
END

To use this user-defined function (for example to convert 30 Meters per Second to Kilometers per Hour):

SELECT dbo.ufn_mps2kmph (30)

ufn_mps2kmph

If the post helped you, please share it:
Pin It

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">