Microsoft SQL Server Cast


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


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)


DECLARE @C varchar(2)  = 'a'    

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

Throws error if failed