Logo 
Search:

SQL Server Articles

Submit Article
Home » Articles » SQL Server » System FunctionsRSS Feeds

CAST Function

Posted By: Sarita Patel     Category: SQL Server     Views: 21063

This article explains about CAST function in sql server with examples.

CAST function is used to explicitly convert an expression of one data type to another. 


Syntax of CAST Function :

CAST ( expression AS data_type )

expression is any valid sql server expression.

data_type is sql server data type to convert expression into that data type.




Examples of CAST Function :

Example 1 : Use of CAST function in select clause 

SELECT CAST ( 10.20 AS INT )

Output
10

Above example converts 10.20 float value into an integer value and returns 10.




Example 2 : Use of CAST function to convert table column value in select clause


SELECT ProductName, UnitPrice, CAST(UnitPrice AS INT) AS AroundPrice
FROM    Products

Output
ProductName                             UnitPrice    AroundPrice
Queso Manchego La Pastora         38.00          38
Konbu                                         6.00            6
Tofu                                           23.25          23
Genen Shouyu                             15.50          16
Pavlova                                       17.45          17
Alice Mutton                                39.00          39
Carnarvon Tigers                         62.50          63
Teatime Chocolate Biscuits             9.20            9
 

Above example returns converted unitprice in an integer value named as AroundPrice of table products.




Example 3 : Use of CAST function in where clause 


SELECT ProductName, UnitPrice 
FROM    Products
WHERE  CAST(UnitPrice AS INT) = 10

Output
ProductName                                           UnitPrice
Aniseed Syrup                                          10.00
Sir Rodney's Scones                                 10.00
Jack's New England Clam Chowder               9.65
Rogede sild                                               9.50
Zaanse koeken                                           9.50
Longlife Tofu                                            10.00

Above example returns all products whose unit price is approximately or equal to $10.
  
Share: 

 
 
 

Didn't find what you were looking for? Find more on CAST Function Or get search suggestion and latest updates.

Sarita Patel
Sarita Patel author of CAST Function is from United States.
 
View All Articles

 
Please enter your Comment

  • Comment should be atleast 30 Characters.
  • Please put code inside [Code] your code [/Code].

 
No Comment Found, Be the First to post comment!