In SQL, CAST function is used to convert a value from one data type to another data type.
CAST(expression AS data_type)
• Specify the 'expression/value' that you want to convert from one data type to another.
• Specify the desired 'data type' to which you want to convert the value or expression.
1. Let's assume we have a table named "[Employees]".
2. Let's assume you want to convert the Joining_Date values from datetime format to date format.
3. Run below SQL statement :
SELECT *, CAST(Joining_Date AS date) AS [Date] FROM [Employees];
4. In above statement, CAST function converts the Joining_Date values from datetime format to date format.
Using this function in a select statement won't modify the [Employees] table directly, but it will only be reflected in the select statement's output.
The CAST function in SQL converts data from one data type to another.
The main difference between CAST and CONVERT in SQL is that CAST is ANSI standard while CONVERT is specific to SQL Server.
In SQL-92, the CAST function is used for type conversion.
In SQL, the CAST function for decimals converts data to a decimal data type.