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

To create a User Defined Function (UDF) that converts speed from Kilometers per Hour to Miles 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_kmph2mph] (@kmph decimal(10,3))
RETURNS decimal(10,3)
AS
BEGIN
RETURN (@kmph * 0.621371)
END

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

SELECT dbo.ufn_kmph2mph (120)

ufn_kmph2mph

To create a User Defined Function (UDF) that converts speed from Miles per Hour 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_mph2kmph] (@mph decimal(10,3))
RETURNS decimal(10,3)
AS
BEGIN
RETURN (@mph * 1.60934)
END

To use this user-defined function (for example to convert 90 Miles per Hour to Kilometers per Hour):

SELECT dbo.ufn_mph2kmph (90)

ufn_mph2kmph

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="">