SQL Server CAST() Function
Last Updated :
13 Feb, 2024
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.
What is the CAST() Function?
The SQL server CAST() function allows you to explicitly convert data from one data type to another. Whether you need to change a string to a number, adjust the precision of a decimal, or alter the format of a date, the CAST() function provides the flexibility to manipulate your data to meet specific requirements. Understanding how to use this function effectively can streamline your data management processes and enhance the accuracy of your database queries. The syntax of the CAST() function is as follows:
CAST ( expression AS data_type [ ( length ) ] )
Here:
- expression represents the value to be converted.
- data_type denotes the target data type to which the expression will be converted.
- length (optional) specifies the length of the target data type, particularly relevant for character data types like VARCHAR. The default value is 30.
The CAST() function can convert values of any data type to one of the following data types: bigint, int, smallint, tinyint, bit, decimal, numeric, money, smallmoney, float, real, datetime, smalldatetime, char, varchar, text, nchar, nvarchar, ntext, binary, varbinary, or image.
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:
Convert String to Integer using Cast() functionExplaination: 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:
Convert String to Date using Cast() functionExplaination: 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:
Convert Integer to Bit using Cast() functionExplaination:
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
Conclusion
The CAST() function in SQL Server is a versatile tool for data transformation tasks. By understanding its usage and syntax, you can seamlessly convert data between different types to suit your specific needs. Its ability to transform data types with precision and control enhances the flexibility and efficiency of database operations. Whether it's converting strings to numbers, adjusting decimal precision, or handling other data type conversions, CAST() empowers SQL developers to tackle diverse data challenges with ease.
Similar Reads
SQL Server DATEDIFF() Function
The DATEDIFF() function in SQL Server is a powerful tool used to calculate the difference between two dates or times. It returns an integer representing the number of date or time boundaries crossed between the specified dates, based on the specified date. This function is essential for tasks that i
4 min read
SQL Server TRY CONVERT() Function
When we deal with databases, we come across different data types. In SQL we have various data types to store different types of data. Like int data type for integers, varchar data type for strings, date data type for storing the data, and XML for XML type data. For such types of data conversions, we
6 min read
SQL Server POWER() Function
The POWER() function in SQL Server is a mathematical function that computes the result of raising a number (the base) to the power of another number (the exponent). It is a versatile function used for various calculations, such as squaring a number, computing roots or applying exponential growth in
4 min read
SUM() Function in SQL Server
The SUM() function in SQL Server is an essential aggregate function used to calculate the total sum of values in a numeric column. It aggregates data by summing up all values in the specified column for the rows that match the criteria of the query. In this article, We will learn about SUM() Functio
3 min read
SQL Server Group Functions
The group function in SQL Server provides a powerful tool for performing calculations on groups of rows, allowing you to group data based on specific criteria. This function is important when you want to analyze and summarize information from multiple records in a data structure. The basic group fun
3 min read
SIGN() Function in SQL Server
In SQL Server, the SIGN() function is a mathematical function used to determine the sign of a given numeric expression. This function is particularly useful when we want to evaluate whether a number is positive, negative or zero. In this article, We will learn about SIGN() Function in SQL Server in
3 min read
YEAR() Function in SQL Server
The YEAR() function in SQL Server is a powerful tool designed to extract the year component from a given date or datetime expression. It allows users to isolate the year as an integer value and facilitating various date-related operations and analyses. In this article, We will learn about the YEAR()
2 min read
SQL | Date Functions (Set-2)
SQL Date Functions are powerful tools that allow users to manipulate, extract , and format date and time values within SQL databases. These functions simplify handling temporal data, making them indispensable for tasks like calculating intervals, extracting year or month values, and formatting dates
5 min read
SQL | Date Functions (Set-1)
SQL Date Functions are essential for managing and manipulating date and time values in SQL databases. They provide tools to perform operations such as calculating date differences, retrieving current dates and times and formatting dates. From tracking sales trends to calculating project deadlines, w
5 min read
SQL Server TRY PARSE() Function
SQL Server is a Relational Database Management System(RDBMS), which is used to handle, manage and utilize the data of organizations and so on. It provides various effective functions to manage things efficiently and gives exceptional output. In this article, we will understand one of the important f
8 min read