SQL Server CAST() Function

The CAST() function in SQL Server converts a value from one data type to another. This is a crucial operation for data manipulation, ensuring that your data is in the correct format for calculations, comparisons, or display.



CAST(): Definition and Usage

CAST() allows you to change the data type of a value. You specify the expression to convert and the target data type. It's a flexible way to manage data types in your SQL queries. For more complex conversions (particularly those involving formatting options for dates and times), the CONVERT() function offers more options.

Syntax

Syntax

CAST(expression AS datatype(length))
      

Parameter Values

Parameter Description
expression The value or expression you want to convert. This is required.
datatype(length) The target data type (e.g., int, varchar(20), datetime). The length is optional for some data types (e.g., varchar). This is required.

Examples

Converting to Integer

Converting the floating-point number 25.65 to an integer. Note that the fractional part is truncated (not rounded).

Syntax

SELECT CAST(25.65 AS int);
      
Output

25
      

Converting to VARCHAR

Converting a number to a string.

Syntax

SELECT CAST(25.65 AS varchar);
      
Output

25.65
      

Converting a String to DATETIME

Converting a date string to a datetime value.

Syntax

SELECT CAST('2017-08-25' AS datetime);
      
Output

2017-08-25 00:00:00.000