Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MS SQL server casting without exception

Is there any "convert" function in MS SQL server that allows to cast types safely(without throwing exception). I need something like "tryParse" in C# lang but as SQL statement.

More detailed, I need the following statement returns zero or any else but throwing exception.

select convert(float, 'fjsdhf')

thanks in advance.

like image 434
AndrewG Avatar asked Jun 25 '09 09:06

AndrewG


People also ask

What is the difference between CAST and convert in SQL?

The CAST function is used to convert a data type without a specific format. The CONVERT function does converting and formatting data types at the same time.

What is the difference between Try_convert and convert?

If the cast fails, the TRY_CONVERT() function returns NULL while the CONVERT() function raises an error. This is the main difference between the two functions. You can use the NULL handling functions or expressions such as ISNULL() and COALESCE to handle the result of the TRY_CONVERT() function in case the cast fails.

Is CAST faster than convert?

In our demo, that is performed using three different data types conversions, it can be found that CAST is the fastest function that can be used to convert the data type of the provided value, and the PARSE function is the slowest.


2 Answers

This will default non-numerics to 0 and will not require another statement:

 SELECT CASE      WHEN ISNUMERIC(myvarcharcolumn)=1 THEN         CONVERT(float, REPLACE(LTRIM(RTRIM(myvarcharcolumn)), ',', '.'))      ELSE 0 END AS myfloatcolumn 

The REPLACE() function call is used to change commas to periods. Commas are used in some cultures as a decimal separator (e.g., "1,25" instead of "1.25"), but unless your server is set up with one of those as the default culture, ISNUMERIC() will return 1 but CONVERT() will throw an error. This does mean that your strings should not use commas as thousands separators, but in most cases, a comma for a decimal placeholder is more likely to be a decimal placeholder.

The LTRIM(RTRIM()) call is because ISNUMERIC() will return 1 for a string with leading or trailing spaces, but CONVERT() can't deal with them. So, you must trim your strings.

The only remaining potential issue is that ISNUMERIC() will return 1 if the number can be represented as an int, currency, decimal, or float, but you're only converting to a float. Realistically, a float can store just about anything you throw at it, but if you were trying to convert to an int instead, ISNUMERIC() would return 1 for a value like "2.5", but CONVERT(int, '2.5') will still throw an error.

like image 92
richardtallent Avatar answered Sep 19 '22 18:09

richardtallent


In SQL SERVER 2012 there are new functions to deal with this

try_cast try_convert try_parse

like image 31
Devin Garner Avatar answered Sep 23 '22 18:09

Devin Garner