Skip to content

CastAndConvert

CAST() :

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

1
select CAST ( [Expression] AS Datatype) 
1
2
3
4
5
6
7
8
ex:
DECLARE @A varchar(2)  
DECLARE @B varchar(2)  
DECLARE @C varchar(2)  
set @A=25  
set @B=15  
set @C=33  
Select CAST(@A as int) + CAST(@B as int) +CAST (@C as int) as Result 

CONVERT() :

Both cast and convert functions are used to convert one datatype into another datatype , but convert functions is used for different date formats.

1
select CONVERT(data_type(length), expression, style)
1
2
3
4
5
ex:
In this example we take a style value 108 which defines the following format: 
hh:mm:ss

select convert(varchar(20),GETDATE(),108) 
1
2
3
4
5
ex:
In this example we use the style value 107 which defines the following format:
Monthname dd, yy

select convert(varchar(20),GETDATE(),107)