Conversion Functions – CAST()

I am going press on with my series of articles (tidbits) on type conversion functions available in the Transaction SQL (T-SQL) language.

One analogy of a data type conversion is apply the correct action to change the physical form of water (H2O). You can convert water to ice by cooling it. You can convert water to vapor by heating it. However, the chemical composition of water is still the same!

Information is stored in a database as rows in a table. Each field in a table is defined with a certain data type. The original designer of the database schema might not be aware of all potential uses of the stored information. Therefore, it is not uncommon as a developer to convert data from one type to another.

Today, I want to talk about how to use CAST function which takes a source data value and a target data type as parameters. It returns the the source data value casted to the target data type.

The TSQL example below shows valid and invalid conversions for strings, numbers, and dates.

The output from the TSQL example is shown below.

Here are the results from executing the TSQL example.

  1. The large string is converted to a smaller string. Truncation occurs as a side effect of the operation. No warning is produced.
  2. I am storing 2 raised to the 16th power as a integer. Casting the larger number to a smaller number results in a arithmetic overflow. A error is raised because of this operation.
  3. I am able to cast a string to a date. However, converting the date stored as a 4 byte hex code to a date data type fails. A error is raised because this conversion is not allowed.

Please note the CAST function uses the following matrix to transform data from one form to another.

Next time, I will be talking about the PARSE function that takes a source string, a target data type, and a optional culture information as parameters. It returns the target data type containing the transformed source string.

Related posts

Leave a Comment