SQL Server Convert function Example
This example will explain the SQL Server Convert function with its syntax and a proper example.
SQL Server is relational database management (RDBMS). Microsoft has developed the SQL Server. Many of the Database Management Systems use SQL, and SQL Server is not different.
1. Pre-requisites
To run this example, you should have SQL Server downloaded and installed on your local machine.
2. What is the SQL Server Convert function?
In SQL Server, the Convert() converts the data type from one type to another type. If the conversion is successful, then the function returns the converted value. Otherwise, the function will return an error.
3. SQL Server Convert() Syntax
The syntax for the Convert() function is as follows:
CONVERT( datatype(length), expression , style)
Let us now look at the three parameters in detail.
- Datatype – It is the data type you want the original data to convert into. This is a required parameter. This can be any value like
int
,bit
,decimal
,char
,float
,numeric
, and many others. The length value is not a required parameter. You may or may not include it. Primarily the data types likechar
,varchar
,nchar
use it. - Expression – This is the value that you want to convert into the new data type. This is a required argument.
- Style – This is also an optional parameter. Style parameter converts the date format or string into a specific format.
4. Example
The example below shows the usage of Convert() to convert the different data types.
Example
SELECT CONVERT(int, 19.22);
SELECT CONVERT(float, 14.29);
SELECT CONVERT(varchar, 1020);
SELECT CONVERT(varchar(2), 'HELLO');
SELECT CONVERT(int, '1');
SELECT CONVERT(datetime, '2020-10-12');
SELECT CONVERT(varchar, '10/02/2020',101);
Output
19 14.29 1020 HE 1 2020-10-12 00:00:00.000 10/02/2020
5. Summary
In this article, we learned about the functionality and usage of the SQL Server Convert function. The Convert() function is used to convert from one data type to another. And, we can do this for several data types. We also implemented the Convert() function using different arguments for different data types.
6. Download the source code
You can download the source code from the link given below.
You can download the full source code of this example here: SQL Server Convert function Example