Open In App

Casting value or an expression from one data type to another in SQL server

SQL Server uses the CAST() function to cast or convert a value or an expression from one data type to another.

Syntax :



CAST ( value AS targettype [ ( length ) ] )

Parameters used :

For better understanding, let us run the below query as follows.

SELECT 3 + '3' AS Result;

Output :

Result
6

Its result is 6 as a number. In above statement, SQL Server implicitly converts the character string ‘3’ to the number 3.

Note –
When two values with different data types are used in SQL Server, it will convert the lower to higher data type before it process if further. This is known as implicit conversion.

On the other hand, SQL server could use explicit conversions where the CAST() function is used explicitly to convert a value of one type to another as follows.

SELECT 3 + CAST('3' AS INT) AS Result;

Output :

Result
6

To cast a value of the data types in different scenarios, SQL Server will return a truncated value or a rounded value based on the following rules as follows.

From Data Type   To Data Type Behavior
numeric numeric Round
numeric int Truncate
float int Round
float numeric Round
float datetime Round
datetime int Round

Examples –

Article Tags :
SQL