CONVERT() function in SQL Server

 

The CONVERT() function converts one data type to another. It has two parameters, the first parameter of the function is the data type to which you wish the existing column or expression to be converted.

SQL Server will attempt to convert like data types to the proper type automatically when it can, otherwise it returns an error message that suggest  the use of CONVERT().

Example:

Suppose we have a table ‘tbl_employee’

Table name: tbl_Employee

Employee IdEmpNameSalaryDepartment
1Ankur1200Sales
2David3400Sales
3John1500HR
4James1200Production
5Mohan4500Production
6Ram2300HR

See the following query ( we create a Employee code  with the help of Employee name and Employee id).

SELECT EmpName,

CONVERT(CHAR(1),Employee Id)  + ‘-‘ + LEFT(EmpName,3) AS “Employee Code”

FROM tbl_Employee

 

Output Will be:

EmpNameEmployee Code
AnkurAnk-1
DavidDav-2
JohnJoh-3
JamesJam-4
MohanMoh-5
RamRam-6

One more important use of this function is to specify the format of a date field when converting it to CHAR or VARCHAR from DATETIME .

SQL Server string to datetime conversion /convert char to date  / convert varchar to date

Example

SELECT convert(datetime, ‘Oct 23 2012 11:01AM’)

mm/dd/yyyy format

SELECT convert(datetime, ’10/23/2016′)

yyyy.mm.dd format

SELECT convert(datetime, ‘2016.10.23’)

 
The CONVERT() function can be used to display datetime data in different formats by using an additional parameter.
Then you can use the CONVERT() function as:
 
CONVERT(data-type, _expression, _style)
 
where
data-type is Specifies the target data type (with an optional length).
_expression is Specifies the value to be converted.
_style is Specifies the output format for the date/time.