In SQL Server, both the cast and CONVERT functions are available for type conversions, and their functions are the same.
It's just a different syntax.
Cast is generally easier to use, and the advantage of convert is that dates and values can be formatted.
1 Select CAST('123' as int)--1232 Select CONVERT(int,'123')--1233 4 Select CAST(123.4 as int)--1235 Select CONVERT(int,123.4)--1236 7 Select CAST('123.4' as int)8 Select CONVERT(int,'123.4')9 --Conversion failed when converting the varchar value ' 123.4 ' to data type int.Ten One Select CAST('123.4' as decimal)--123 A Select CONVERT(decimal,'123.4')--123 - - the Select CAST('123.4' as decimal(9,2))--123.40 - Select CONVERT(decimal(9,2),'123.4')--123.40 - - + Declare @Num Money - Set @Num = 1234.56 + Select CONVERT(varchar( -),@Num,0)--1234.56 A Select CONVERT(varchar( -),@Num,1)--1,234.56 at Select CONVERT(varchar( -),@Num,2)--1234.5600
Convert is generally used in time conversion because it adds a style to the cast and can be converted to a different time format
CONVERT (data_type (length),data_to_be_converted,style)
data_type (length) Specifies the target data type (with optional lengths). The data_to_be_converted contains values that need to be converted. style Specifies the date/time output format.
The style value that can be used:
1 CONVERT(VARCHAR( +),GETDATE())2 CONVERT(VARCHAR(Ten),GETDATE(), the) 3 CONVERT(VARCHAR( One),GETDATE(),106)4 CONVERT(VARCHAR( -),GETDATE(),113)
The difference between cast and convert forced type conversions in SQL Server