Microsoft SQL Server Converting data types Cast

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

The Cast() function is used to convert a data type variable or data from one data type to another data type.

Syntax

CAST ( [Expression] AS Datatype)

The data type to which you are casting an expression is the target type. The data type of the expression from which you are casting is the source type.

DECLARE @A varchar(2)    
DECLARE @B varchar(2)

set @A='25a'    
set @B='15'

Select CAST(@A as int) + CAST(@B as int)  as Result 
--'25a' is casted to 25 (string to int)
--'15' is casted to 15 (string to int)

--Result 
 --40

DECLARE @C varchar(2)  = 'a'    

select CAST(@C as int) as Result    
--Result
 --Conversion failed when converting the varchar value 'a' to data type int.

Throws error if failed



Got any Microsoft SQL Server Question?