Data Type Conversion
In Transact-SQL, two levels of data type conversions are possible:
- When data from one object is moved to, compared with, or combined with data from another object, the data may have to be converted from the data type of one object to the data type of the other.
- When data from a Transact-SQL result column, return code, or output parameter is moved into a program variable, it must be converted from the Microsoft® SQL Server™ data type to the data type of the variable.
There are two categories of data type conversions:
- Implicit conversions are invisible to the user.
SQL Server automatically converts the data from one data type to another. For example, if a smallint is compared to an int, the smallint is implicitly converted to int before the comparison proceeds.
- Explicit conversions use the CAST or CONVERT functions.
The CAST and CONVERT functions convert a value (a local variable, a column, or another expression) from one data type to another. For example, the following CAST function converts the numeric value of $157.27 into a character string of '$157.27':
CAST ( $157.27 AS VARCHAR(10) )
CAST is based on the SQL-92 standard and is preferred over CONVERT.
When converting from the data type of one SQL Server object to another, some implicit and explicit data type conversions are not supported. For example, an nchar value cannot be converted to an image value at all. An nchar can only be converted to binary using explicit conversion; an implicit conversion to binary is not supported. An nchar can be either explicitly or implicitly converted to nvarchar.
When handling sql_variant data types, SQL Server supports implicit conversions of objects with other data types to sql_variant type. However, SQL Server does not support implicit conversions from sql_variant data to an object with another data type.
For more information about supported conversions between SQL Server objects, see CAST and CONVERT.
When converting between an application variable and an SQL Server result set column, return code, parameter, or parameter marker, the supported data type conversions are defined by the database application programming interface.