Examples of Using the CAST() Function
Let’s see some examples of how to use the CAST() function in SQL Server.
Example 1: Convert a String Value to an Integer
Suppose we have a decimal value ‘123’ and we want to convert it to an integer. We can use the CAST() function as follows:
SELECT CAST('123' AS INT) AS IntegerValue;
Output:
Explaination: In this Example, The provided SQL query uses the CAST function to convert the string ‘123’ to an integer. The result, named IntegerValue, is the integer representation of the given string, which is 123.
Example 2: Convert a String Value to a Date
Suppose we have a date value 2024-02-08′ and we want to convert it to a varchar. We can use the CAST() function as follows:
SELECT CAST('2024-02-08' AS DATE) AS ConvertedDate;
Output:
Explaination: In this Example a string representing a date(‘2024-02-08’) is cast to the DATE data type.
Example 3: Convert a Integer Value to an Bit Value
Suppose we have a Integer value 1 and we want to convert it to a Bit. We can use the CAST() function as follows:
SELECT CONCAT('The bit value is: ', CAST(1 AS bit)) AS BitValue;
Output:
Explaination:
In the provided example, we’re using the CONCAT() function along with the CAST() function to create a string that includes both text and a converted value. CAST() function convert the integer value 1 to a bit data type
SQL Server CAST() Function
In SQL Server, manipulating data is a fundamental aspect of database management. Often, you’ll find yourself needing to transform data from one type to another, either for calculations, comparisons, or presentation purposes. This is where the CAST() function comes. In this article, we will learn about the CAST() function in SQL Server, which is used to convert a value from one data type to another.