Conversion Functions – PARSE()

I am going to continue the 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 the PARSE function which 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.

The TSQL example below shows valid and invalid conversions. Since I am not familiar with the presentation of German dates and times, I used the FORMAT function to create me the strings for use in my code.

The output from the TSQL example is shown below.

Here are the results from executing the TSQL example.

  1. I was able to convert £45.99 pounds to a money data type when using the Great Britain cultural format. However, it fails when using the English cultural format. We use dollars in America!
  2. I was able to generate both a full date string as well as a numeric date string in the German language.
  3. Using German as the cultural format, I was able to convert the prior strings to both a DATE and TIME data type.

In summary, the PARSE function is used to convert strings to other data types. Cultural specific information for money, date, or time formatting can be accounted for.

Next time, I will be talking about the TRY_CONVERT function. This function was introduced in SQL Server 2012. Unlike its cousin, invalid casting of data results in a NULL value instead of an ERROR.

Related posts

Leave a Comment