Changing data from one data type to another is commonly used to display dates in a format that differs to that the way it’s stored, or when joining two tables on columns that store the same data, but in different formats.
The CAST and CONVERT System Functions essentially achieve the same task, with a few small difference.
CAST is the ANSI compliant version of the two. CAST can change data from one type to another, but cannot change the format of a date. It’s simple to use, and it’s syntax is as follows:
CAST ( Expression AS Target Data Type )
Where I’ve written “Expression”, you would replace with either a column name, or a hardcoded value (Such as a value of 7). “Target Data Type” would be replaced with the name of the Data Type that you’d like to convert the value to.
CONVERT works in a similar manner, but has one more optional value available and is not ANSI standard.
CONVERT ( Target Data Type, Expression, Style )
As above, Target Data Type is the data type that you’d like to convert to, and Expression is the column or hardcoded value. You’ll notice that this example also includes Style. This option is available when working with dates. For example, most of the time dates are stored as a DateTime which would look like “2001-01-01 00:00:00:000″. If you wanted to exclude the time and display the date as “01 Jan 2001″ you’d use:
CONVERT ( VARCHAR(11), '2001-01-01 00:00:00:000', 106 )
Not all data types can be converted or cast to all data types, for example a Bit cannot be converted to an Image.
Below is a table of some of the more common Date Styles used, and an example of how the output will look. All of the examples use 2001-01-01.
| Style Number | Date Output Example |
| 101 | 01-01-2001 (MM/DD/YYYY) |
| 103 | 01-01-2001 (DD/MM/YYYY) |
| 106 | 01 Jan 2001 (DD MON YYYY) |
| 107 | Jan 01, 2001 (MON DD, YYYY) |
