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 Interview Questions Are you preparing for a SQL interview? SQL is a standard database language used for accessing and manipulating data in databases. It stands for Structured Query Language and was developed by IBM in the 1970s, SQL allows us to create, read, update, and delete data with simple yet effective commands.
15+ min read
SQL Tutorial SQL is a Structured query language used to access and manipulate data in databases. SQL stands for Structured Query Language. We can create, update, delete, and retrieve data in databases like MySQL, Oracle, PostgreSQL, etc. Overall, SQL is a query language that communicates with databases.In this S
11 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
SQL Joins (Inner, Left, Right and Full Join) SQL joins are fundamental tools for combining data from multiple tables in relational databases. Joins allow efficient data retrieval, which is essential for generating meaningful observations and solving complex business queries. Understanding SQL join types, such as INNER JOIN, LEFT JOIN, RIGHT JO
6 min read
Normal Forms in DBMS In the world of database management, Normal Forms are important for ensuring that data is structured logically, reducing redundancy, and maintaining data integrity. When working with databases, especially relational databases, it is critical to follow normalization techniques that help to eliminate
8 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
ACID Properties in DBMS In the world of Database Management Systems (DBMS), transactions are fundamental operations that allow us to modify and retrieve data. However, to ensure the integrity of a database, it is important that these transactions are executed in a way that maintains consistency, correctness, and reliabilit
8 min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read