Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using IF IsNumeric as Argument

i was wondering how to use IsNumeric in SQL, it's a bit different from VBScript, but i think i was able to get around it, ie:

 IF 1 = ISNUMERIC('5675754674') 
 BEGIN 
 ...
 END

Would this be a way around it? What I really want to do is:

IF ISNUMERIC('5675754674')
BEGIN 
... 
END

but that gives an error. Example 1 seems to work, but just making sure i'm doing this right, wasn't able to find any good resources online about it.

like image 916
Control Freak Avatar asked Feb 15 '12 00:02

Control Freak


People also ask

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.

How do I check if a value is numeric in SQL?

The ISNUMERIC() function tests whether an expression is numeric. This function returns 1 if the expression is numeric, otherwise it returns 0.

Which function tests whether a value is numeric or nonnumeric?

Since not only exact numbers are considered valid numeric data types, the ISNUMERIC function will return 1 even if the expression contains some symbols and alphabets.


1 Answers

There is no boolean in SQL Server. This means you can't just say IF (expression); you must compare it to something, because it does return true or false in the same sense as you're probably used to in other languages.

Just a preference, but I would prefer to write it this way:

IF ISNUMERIC('5675754674') = 1
BEGIN
...
END

There is no way in SQL Server to avoid the comparison to 1, as in your second example.

Also as an aside you should be aware of the weaknesses of ISNUMERIC() - it can give false positives for "numeric" values such as ., CHAR(9), e, $ and a host of other non-numeric strings. If you want to know if something is an integer, for example, better to say:

IF '5675754674' NOT LIKE '%[^0-9]%'
BEGIN
...
END

But even that is not a complete and valid test because it will return true for values > (2^32)-1 and it will return false for negative values.

Another downside to ISNUMERIC() is that it will return true if the value can be converted to any of the numeric types, which is not the same as all numeric types. Often people test for ISNUMERIC() and then try to cast a FLOAT to a SMALLINT and the conversion fails.

In SQL Server 2012 you will have a new method called TRY_CONVERT() which returns NULL if the conversion to the specified data type is not valid.

like image 91
Aaron Bertrand Avatar answered Oct 19 '22 05:10

Aaron Bertrand