Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server's ISNUMERIC function

I need to checking a column where numeric or not in SQL Server 2012.

This my case code.

CASE
    WHEN ISNUMERIC(CUST_TELE) = 1 
      THEN CUST_TELE 
      ELSE NULL 
END AS CUSTOMER_CONTACT_NO

But when the '78603D99' value is reached, it returns 1 which means SQL Server considered this string as numeric.

Why is that?

How to avoid this kind of issues?

like image 876
weeraa Avatar asked Aug 21 '15 08:08

weeraa


People also ask

What is IsNumeric function SQL Server?

ISNUMERIC() function: This function in SQL Server is used to check if the stated expression is numeric or not. Features: This function is used to check if the given expression is numeric or not. This function returns 1 if the given expression is in numerical form.

What can I use instead of IsNumeric?

Avoid using the IsNumeric() function, because it can often lead to data type conversion errors, when importing data. On SQL Server 2012 or later, use the Try_Convert() or Try_Cast() function instead.

What type of data is returned by the IsNumeric function?

Returns a Boolean value indicating whether an expression can be evaluated as a number. The required expressionargument is a Variant containing a numeric expression or string expression. IsNumeric returns True if the entire expression is recognized as a number; otherwise, it returns False.


2 Answers

Unfortunately, the ISNUMERIC() function in SQL Server has many quirks. It's not exactly buggy, but it rarely does what people expect it to when they first use it.

However, since you're using SQL Server 2012 you can use the TRY_PARSE() function which will do what you want.

This returns NULL: SELECT TRY_PARSE('7860D399' AS int)

This returns 7860399 SELECT TRY_PARSE('7860399' AS int)

https://msdn.microsoft.com/en-us/library/hh213126.aspx

Obviously, this works for datatypes other than INT as well. You say you want to check that a value is numeric, but I think you mean INT.

like image 181
Paul Spangle Avatar answered Oct 19 '22 11:10

Paul Spangle


Although try_convert() or try_parse() works for a built-in type, it might not do exactly what you want. For instance, it might allow decimal points, negative signs, and limit the length of digits.

Also, isnumeric() is going to recognize negative numbers, decimals, and exponential notation.

If you want to test a string only for digits, then you can use not like logic:

(CASE WHEN CUST_TELE NOT LIKE '%[^0-9]%'
      THEN CUST_TELE 
 END) AS CUSTOMER_CONTACT_NO

This simply says that CUST_TELE contains no characters that are not digits.

like image 29
Gordon Linoff Avatar answered Oct 19 '22 12:10

Gordon Linoff