User Defined Function (UDF) to Convert Area between Square Kilometers and Square Miles in SQL Server

To create a User Defined Function (UDF) that converts area from Square Kilometers to Square Miles, that uses decimal(10,4) data type with precision 10 and scale 4 for input and output area values, use the following command:

CREATE FUNCTION [dbo].[ufn_sqkm2sqmi] (@sqkm decimal(10,4))
RETURNS decimal(10,4)
AS
BEGIN
RETURN (@sqkm * 0.386102)
END

To use this user-defined function (for example to convert 22.7641 square kilometers to square miles):

SELECT dbo.ufn_sqkm2sqmi (22.7641)

ufn_sqkm2sqmi

To create a User Defined Function (UDF) that converts area from Square Miles to Square Kilometers, that uses decimal(10,4) data type with precision 10 and scale 4 for input and output area values, use the following command:

CREATE FUNCTION [dbo].[ufn_sqmi2sqkm] (@sqmi decimal(10,4))
RETURNS decimal(10,4)
AS
BEGIN
RETURN (@sqmi * 2.58999)
END

To use this user-defined function (for example to convert 122.7141 square miles to square kilometers):

SELECT dbo.ufn_sqmi2sqkm (122.7141)

ufn_sqmi2sqkm