This SQL Server tutorial explains how to use the ISNUMERIC function in SQL Server (Transact-SQL) with syntax and examples.
Description
In SQL Server (Transact-SQL), the ISNUMERIC function returns 1 if the expression is a valid number. Otherwise, it returns 0.
Syntax
The syntax for the ISNUMERIC function in SQL Server (Transact-SQL) is:
ISNUMERIC( expression )
Parameters or Arguments
- expression
- The value to test whether it is a numeric value.
Note
- The ISNUMERIC function returns 1, if the expression is a valid number.
- The ISNUMERIC function returns 0, if the expression is NOT a valid number.
Applies To
The ISNUMERIC function can be used in the following versions of SQL Server (Transact-SQL):
- SQL Server 2017, SQL Server 2016, SQL Server 2014, SQL Server 2012, SQL Server 2008 R2, SQL Server 2008, SQL Server 2005
Example
Let’s look at some SQL Server ISNUMERIC function examples and explore how to use the ISNUMERIC function in SQL Server (Transact-SQL).
For example:
SELECT ISNUMERIC(1234); Result: 1 SELECT ISNUMERIC('1234'); Result: 1 SELECT ISNUMERIC(10 * 5); Result: 1 SELECT ISNUMERIC('techonthenet.com'); Result: 0 SELECT ISNUMERIC('2014-05-01'); Result: 0
How do I check if a string in a MySQL field contains a number then delete them?
Example table:
tbl_tags
-------------
| id | tag |
-------------
| 1 | hello |
| 2 | hello2 |
| 3 | 2hello |
| 4 | hel3lo |
-------------
The only way I can think of is to do each number individually and use LIKE ‘%1%’ OR LIKE ‘%2%’ etc. But there must be an easier way?
asked Jul 17, 2010 at 1:37
Check out the MySQL Regex methods. Something like the following should work.
SELECT * FROM table WHERE tag REGEXP '[0-9]'
answered Jul 17, 2010 at 1:39
Jason McCrearyJason McCreary
71.2k23 gold badges133 silver badges174 bronze badges
1
SELECT *
FROM clients
WHERE name REGEXP '^[[:digit:]]+$'
ORDER BY `clients`.`country_id` DESC
LIMIT 0 , 30
this is the answer if you’re looking for strings with only digits
r3mainer
23.8k3 gold badges50 silver badges86 bronze badges
answered Jan 16, 2014 at 1:30
1
Is there an easy way to figure out if a varchar is a number?
Examples:
abc123 —> no number
123 —> yes, its a number
asked Jan 5, 2011 at 10:59
4
ISNUMERIC will not do — it tells you that the string can be converted to any of the numeric types, which is almost always a pointless piece of information to know. For example, all of the following are numeric, according to ISNUMERIC:
£, $, 0d0
If you want to check for digits and only digits, a negative LIKE expression is what you want:
not Value like '%[^0-9]%'
answered Jan 5, 2011 at 11:10
6
ISNUMERIC will do
Check the NOTES section too in the article.
answered Jan 5, 2011 at 11:03
Sachin ShanbhagSachin Shanbhag
54.1k11 gold badges88 silver badges103 bronze badges
6
You can check like this:
declare @vchar varchar(50)
set @vchar ='34343';
select case when @vchar not like '%[^0-9]%' then 'Number' else 'Not a Number' end
answered Jan 5, 2011 at 11:09
BinilBinil
6,4253 gold badges30 silver badges40 bronze badges
0
Using SQL Server 2012+, you can use the TRY_* functions if you have specific needs. For example,
-- will fail for decimal values, but allow negative values
TRY_CAST(@value AS INT) IS NOT NULL
-- will fail for non-positive integers; can be used with other examples below as well, or reversed if only negative desired
TRY_CAST(@value AS INT) > 0
-- will fail if a $ is used, but allow decimals to the specified precision
TRY_CAST(@value AS DECIMAL(10,2)) IS NOT NULL
-- will allow valid currency
TRY_CAST(@value AS MONEY) IS NOT NULL
-- will allow scientific notation to be used like 1.7E+3
TRY_CAST(@value AS FLOAT) IS NOT NULL
answered Mar 18, 2016 at 14:55
Dan FieldDan Field
20.7k5 gold badges55 silver badges71 bronze badges
2
I ran into the need to allow decimal values, so I used not Value like '%[^0-9.]%'
bluish
26k27 gold badges120 silver badges179 bronze badges
answered Dec 1, 2014 at 18:20
Wade73Wade73
4,3493 gold badges29 silver badges46 bronze badges
1
Wade73’s answer for decimals doesn’t quite work. I’ve modified it to allow only a single decimal point.
declare @MyTable table(MyVar nvarchar(10));
insert into @MyTable (MyVar)
values
(N'1234')
, (N'000005')
, (N'1,000')
, (N'293.8457')
, (N'x')
, (N'+')
, (N'293.8457.')
, (N'......');
-- This shows that Wade73's answer allows some non-numeric values to slip through.
select * from (
select
MyVar
, case when MyVar not like N'%[^0-9.]%' then 1 else 0 end as IsNumber
from
@MyTable
) t order by IsNumber;
-- Notice the addition of "and MyVar not like N'%.%.%'".
select * from (
select
MyVar
, case when MyVar not like N'%[^0-9.]%' and MyVar not like N'%.%.%' then 1 else 0 end as IsNumber
from
@MyTable
) t
order by IsNumber;
answered Nov 13, 2015 at 21:19
neizanneizan
2,2832 gold badges37 silver badges52 bronze badges
1
Damien_The_Unbeliever noted that his was only good for digits
Wade73 added a bit to handle decimal points
neizan made an additional tweak as did notwhereuareat.
Unfortunately, none appear to handle negative values and they appear to have issues with a comma in the value…
Here’s my tweak to pick up negative values and those with commas
declare @MyTable table(MyVar nvarchar(10));
insert into @MyTable (MyVar)
values
(N'1234')
, (N'000005')
, (N'1,000')
, (N'293.8457')
, (N'x')
, (N'+')
, (N'293.8457.')
, (N'......')
, (N'.')
, (N'-375.4')
, (N'-00003')
, (N'-2,000')
, (N'3-3')
, (N'3000-')
;
-- This shows that Neizan's answer allows "." to slip through.
select * from (
select
MyVar
, case when MyVar not like N'%[^0-9.]%' then 1 else 0 end as IsNumber
from
@MyTable
) t order by IsNumber;
-- Notice the addition of "and MyVar not like '.'".
select * from (
select
MyVar
, case when MyVar not like N'%[^0-9.]%' and MyVar not like N'%.%.%' and MyVar not like '.' then 1 else 0 end as IsNumber
from
@MyTable
) t
order by IsNumber;
--Trying to tweak for negative values and the comma
--Modified when comparison
select * from (
select
MyVar
, case
when MyVar not like N'%[^0-9.,-]%' and MyVar not like '.' and isnumeric(MyVar) = 1 then 1
else 0
end as IsNumber
from
@MyTable
) t
order by IsNumber;
answered Feb 9, 2017 at 17:27
DECLARE @A nvarchar(100) = '12'
IF(ISNUMERIC(@A) = 1)
BEGIN
PRINT 'YES NUMERIC'
END
bluish
26k27 gold badges120 silver badges179 bronze badges
answered Nov 3, 2015 at 5:52
Neizan’s code lets values of just a «.» through. At the risk of getting too pedantic, I added one more AND
clause.
declare @MyTable table(MyVar nvarchar(10));
insert into @MyTable (MyVar)
values
(N'1234')
, (N'000005')
, (N'1,000')
, (N'293.8457')
, (N'x')
, (N'+')
, (N'293.8457.')
, (N'......')
, (N'.')
;
-- This shows that Neizan's answer allows "." to slip through.
select * from (
select
MyVar
, case when MyVar not like N'%[^0-9.]%' then 1 else 0 end as IsNumber
from
@MyTable
) t order by IsNumber;
-- Notice the addition of "and MyVar not like '.'".
select * from (
select
MyVar
, case when MyVar not like N'%[^0-9.]%' and MyVar not like N'%.%.%' and MyVar not like '.' then 1 else 0 end as IsNumber
from
@MyTable
) t
order by IsNumber;
answered Feb 17, 2016 at 17:21
Do not forget to exclude carriage returns from your data!
As in:
SELECT
Myotherval
, CASE WHEN TRIM(REPLACE([MyVal], char(13) + char(10), '')) not like '%[^0-9]%' and RTRIM(REPLACE([MyVal], char(13) + char(10), '')) not like '.' and isnumeric(REPLACE([MyVal], char(13) + char(10), '')) = 1 THEN 'my number: ' + [MyVal]
ELSE ISNULL(Cast([MyVal] AS VARCHAR(8000)), '')
END AS 'MyVal'
FROM MyTable
answered Nov 18, 2019 at 15:21
In case you want to add a constraint on a field:
Positive integer with fixed length
ALTER TABLE dbo.BankBranchType
ADD CONSTRAINT CK_TransitNumberMustBe5Digits
CHECK (TransitNumber NOT like '%[^0-9]%'
AND LEN(TransitNumber) = 5)
answered Aug 16, 2021 at 15:32
To check the Number, Currency, and Amount, use the below SQL fragment.
@value NOT LIKE '%[^0-9.,]%'
For a quick win, refer to the below example:
Function example:
CREATE FUNCTION [dbo].[fnCheckValueIsNumber](
@value NVARCHAR(255)=NULL
)RETURNS INT AS BEGIN
DECLARE @ReturnValue INT=0
IF EXISTS (SELECT * WHERE @value NOT LIKE '%[^0-9.,]%') SELECT @ReturnValue=1
RETURN @ReturnValue;
Execution result
SELECT [dbo].[fnCheckValueIsNumber]('12345')
RESULT = 1
SELECT [dbo].[fnCheckValueIsNumber]('10020.25')
RESULT = 1
SELECT [dbo].[fnCheckValueIsNumber]('10,020.25')
RESULT = 1
SELECT [dbo].[fnCheckValueIsNumber]('12,345ABCD')
RESULT = 0
answered Nov 12, 2022 at 15:46
HaseebHaseeb
7167 silver badges22 bronze badges
In SQL Server, you can use the ISNUMERIC()
function to find out whether an expression is numeric or not.
The function returns 1 if the expression is numeric, and 0 if it’s not.
To use this function, simply pass the value/expression to the function while calling it.
Example 1 – Numeric Expression
Here’s an example to demonstrate what happens when you pass a numeric expression to this function.
SELECT ISNUMERIC(250) AS Result;
Result:
+----------+ | Result | |----------| | 1 | +----------+
In this case, the value is numeric and the result is 1.
We get the same result even if the value is provided as a string (enclosed in single quotes).
SELECT ISNUMERIC('250') AS Result;
Result:
+----------+ | Result | |----------| | 1 | +----------+
Example 2 – Non-Numeric Expression
Here’s what happens when the value is not numeric.
SELECT ISNUMERIC('Hey!') AS Result;
Result:
+----------+ | Result | |----------| | 0 | +----------+
Example 3 – A Database Example
Here’s an example of using ISNUMERIC()
in a WHERE
clause when querying a database:
USE WideWorldImportersDW; SELECT COUNT(*) AS [Count] FROM Dimension.Customer WHERE ISNUMERIC([Postal Code]) = 1;
Result:
+---------+ | Count | |---------| | 402 | +---------+
This returns the count of all rows with a numeric postal code.
Unexpected Results? When Non-Numeric IS Numeric
Some characters are treated as being numeric, even when they’re not a number. This is something you need to be aware of when using this function, otherwise you could get results that you don’t expect.
See Non-Number Characters that Return Positive when using ISNUMERIC()
for an explanation and examples.
В этом учебном пособии вы узнаете, как использовать функцию ISNUMERIC в SQL Server (Transact-SQL) с синтаксисом и примерами.
Описание
В SQL Server (Transact-SQL) функция ISNUMERIC возвращает 1, если выражение является допустимым числом. В противном случае возвращает 0.
Синтаксис
Синтаксис функции ISNUMERIC в SQL Server (Transact-SQL):
ISNUMERIC( expression )
Параметры или аргументы
expression — значение для проверки, является ли это числовым значением.
Примечание
- Функция ISNUMERIC возвращает 1, если expression является допустимым числом.
- Функция ISNUMERIC возвращает 0, если expression НЕ является допустимым числом.
Применение
Функция ISNUMERIC может использоваться в следующих версиях SQL Server (Transact-SQL):
SQL Server vNext, SQL Server 2016, SQL Server 2015, SQL Server 2014, SQL Server 2012, SQL Server 2008 R2, SQL Server 2008, SQL Server 2005
Пример
Рассмотрим некоторые примеры SQL Server функции ISNUMERIC, чтобы понять, как использовать функцию ISNUMERIC в SQL Server (Transact-SQL). Например:
SELECT ISNUMERIC(1234); —Результат: 1 SELECT ISNUMERIC(‘1234’); —Результат: 1 SELECT ISNUMERIC(10 * 5); —Результат: 1 SELECT ISNUMERIC(‘sql server’); —Результат: 0 SELECT ISNUMERIC(‘01.12.2017’); —Результат: 0 |