Click here to Skip to main content
15,881,172 members
Articles / Database Development / SQL Server / SQL Server 2012
Tip/Trick

Checking convertability in SQL Server

Rate me:
Please Sign up or sign in to vote.
4.00/5 (2 votes)
18 Sep 2013CPOL 7.1K   1   1
Avoiding conversion errors in scripts using TRY_CONVERT.

Introduction

We may take a varchar input and to convert it to another data type before inserting/updating to tables. We mostly do an optimistic conversion expecting the varchar value will be in proper convertible format. But this approach can cause exceptions when the input is not in the expected format. 

In SQL Server 2012 a new function has been introduced similar to TryParse in .NET through we can check the convertibility.

TRY_CONVERT 

Let's say we need to check a value can be converted to float:

SQL
SELECT TRY_CONVERT(float,'4.5'

Since  4.5 is convertible to float it will return a float with value of 4.5. 

In below example the value is NA and is not convertible.

SQL
SELECT TRY_CONVERT(float,'NA')

The output will be NULL in this case. 

By using TRY_CONVERT instead of direct CAST or CONVERT we can avoid conversion errors in the scripts.

Read http://technet.microsoft.com/en-us/library/hh230993 for details.

This article was originally posted at http://technet.microsoft.com/en-us/library/hh230993

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- No messages could be retrieved (timeout) --