Temperature conversion SQL Function


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.

 

About Ayyappan Thangaraj

Technology is my passion.
This entry was posted in T-SQL and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s