In this article, I am sharing my code (SQL Function) that converts temperature measure form one to another. My SQL Function take temerature value and its measure charachter (C or F) and returns the other measure.
SQL Code
– =============================================
– Author: Ayyappan Thangaraj, CEO: SQLServerRider.com
– Create date: 12/Jan/2012
– Description: Converts temperature Fahrenheit (°F) / Celsius (°C)
– =============================================
ALTER FUNCTION Convert_Temperature
(
@temperature DECIMAL,
@Degree CHAR –F/C
)
RETURNS DECIMAL
AS
BEGIN
–This function converts temperature vaue from one measure to other.
–If you pass Celsius then it will return Fahrenheit and vice versa.
DECLARE @Result AS DECIMAL
IF UPPER(@Degree) = ‘F’
SET @Result = (@temperature – 32)* 5/ 9 –F to C conversion
IF UPPER(@Degree) = ‘C’
SET @Result = ((@temperature * 9) /5 )+ 32 –C to F Conversion
RETURN @Result
END
Execution
SELECT dbo.convert_temperature (70, ‘F’) AS ‘°C’
SELECT dbo.convert_temperature (21, ‘C’) AS ‘°F’
Result
°C
21
°F
70
Thanks for reading.




