![]() |
VOOZH | about |
The CAST() function is used to convert a value from one data type to another, helping SQL Server work with data in the required format. It is useful when we need to:
The CAST() function makes data flexible, accurate, and easier to manage in SQL queries.
Syntax:
CAST ( expression AS data_type [ ( length ) ] )Let's see some examples of how to use the CAST() function in SQL Server.
Suppose we have a string value '123' and we want to convert it to an integer. We can use the CAST() function as follows:
Query:
SELECT CAST('123' AS INT) AS IntegerValue;Output:
👁 ScreenshotSuppose we have a string value '2024-02-08' and we want to convert it to a DATE. We can use the CAST() function as follows:
Query:
SELECT CAST('2024-02-08' AS DATE) AS ConvertedDate;Output:
Suppose we have an integer value 1 and we want to convert it to a BIT. CAST() converts the value, while CONCAT() is used here only to format the output string.
Query:
SELECT CONCAT('The bit value is: ', CAST(1 AS bit)) AS BitValue;Output:
👁 Screenshot