User Defined Function (UDF) to Convert Temperatures between Fahrenheit and Celsius in SQL Server

To create a User Defined Function (UDF) that converts Temperature from Celsius to Fahrenheit, that uses decimal(5,2) data type with precision 5 and scale 2 for input and output temperature values, use the following command:

CREATE FUNCTION [dbo].[ufn_C2F] (@c decimal(5,2))
RETURNS decimal(5,2)
AS
BEGIN
RETURN (@c * 9.0/5.0)+32
END

To use this user-defined function (for example to convert 12.43 °C to °F):

SELECT dbo.ufn_C2F (12.5)

ufn_C2F

To create a User Defined Function (UDF) that converts Temperature from Fahrenheit to Celsius, that uses decimal(5,2) data type with precision 5 and scale 2 for input and output temperature values, use the following command:

CREATE FUNCTION [dbo].[ufn_F2C] (@f decimal(5,2))
RETURNS decimal(5,2)
AS
BEGIN
RETURN (@f-32)/9.0*5.0
END

To use this user-defined function (for example to convert 52.46 °F to °C):

SELECT dbo.ufn_F2C (52.46)

ufn_F2C