Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a string contains only number

Tags:

sql

sql-server

I am trying to check if a string contains only valid number in the following format

123.456
123
.356

But it should reject anything that contains non-numbers including double dots. Here are some invalid formats

d123.456
123d
12d3
d.1256
12d.456
12.d12
12.d45d
12.45.56

I have done the following

SELECT CASE WHEN '123.00' NOT LIKE '%[^0-9.]%' THEN 'Valid' ELSE 'Invalid' END

When seems to work except for the case where there is more than one dot in the string.

How can I tweak the regular expression to only allow one dot otherwise return 'Invalid'?

like image 577
Junior Avatar asked Jun 01 '16 18:06

Junior


People also ask

How do you check if a string contains only digits in Java?

Using Character. isDigit(char ch). If the character is a digit then return true, else return false.

How do you check if a string contains only letters and numbers?

Use the test() method on the following regular expression to check if a string contains only letters and numbers - /^[A-Za-z0-9]*$/ . The test method will return true if the regular expression is matched in the string and false otherwise.

How do you check if a string contains only numbers Python?

Python String isnumeric() Method The isnumeric() method returns True if all the characters are numeric (0-9), otherwise False. Exponents, like ² and ¾ are also considered to be numeric values. "-1" and "1.5" are NOT considered numeric values, because all the characters in the string must be numeric, and the - and the .


Video Answer


2 Answers

I would suggest try_convert():

select (case when try_convert(col, float) is not null then 'valid' else 'invalid' end)

The one possible downside is exponential format; 1e6 is a valid number for instance.

An alternative is the where approach; you just need more complete logic:

select (case when col like '%[^0-9.]%' then 'invalid'
             when col like '%.%.%' then 'invalid'
             else 'valid'
        end)
like image 90
Gordon Linoff Avatar answered Oct 19 '22 07:10

Gordon Linoff


There's a sql server built in function:

Select CASE WHEN isnumeric([fieldname]) THEN 'Valid' ELSE 'Invalid" END
like image 4
Matt Avatar answered Oct 19 '22 07:10

Matt