SQL Server > Conversion related

Convert a column value from one data type to another in SQL Server

How to convert a column value from one data type to another in SQL Server?


To convert a column value from one data type to another, we use CONVERT function.

This accepts three parameters

  • The target data type to convert to
  • The value to convert to
  • The style number to convert to (optional)                                 

The main difference between CAST and CONVERT is that CONVERT after converting the data type, also apply the formatting number based on value we pass.

SELECT
       Convert(varchar(20), GETDATE()) DefaultFormat,
       Convert(varchar(20), GETDATE(), 101) DDMMYYYY,
       Convert(varchar(20), GETDATE(), 102) YYYYMMDD,
       Convert(varchar(20), GETDATE(), 103) DDMMYYYY,
       Convert(varchar(20), GETDATE(), 104) 
SELECT Convert(varchar(20), GETDATE(), 105),
          Convert(varchar(20), GETDATE(), 106),
          Convert(varchar(20), GETDATE(), 107)

SELECT Convert(varchar(20), GETDATE(), 108),
          Convert(varchar(20), GETDATE(), 109),
          Convert(varchar(20), GETDATE(), 110)

SELECT Convert(varchar(20), GETDATE(), 111),
             Convert(varchar(20), GETDATE(), 112),
             Convert(varchar(20), GETDATE(), 113),
             Convert(varchar(20), GETDATE(), 114)

Notice the 3rd parameter of each CONVERT function and notice the result below.

 Views: 1273 | Post Order: 79



Write for us