Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select only records that have number in column (SQL)

Tags:

sql

sql-server

Basically I want to do this:

I want to return a record set converting one nvarchar value (ID) to an integer if it contains a number. If ID can be converted to a number, then add that row to the SELECT record set. If not, skip that row.

I think the SQL should look something like this.

(ID is nvarchar(10) in dbo.Table)

CREATE TABLE #Temp  (ID int)
INSERT INTO #Temp SELECT ID FROM Table Where ISNumeric(Id)=0

But I get an error: nvarchar value 'Default' to data type int. If I do a SELECT CAST(ID as int) that does not work either.

like image 894
Rob Avatar asked Mar 09 '11 19:03

Rob


People also ask

How do I select only numeric values in a column in SQL?

In SQL Server, we can use the ISNUMERIC() function to return numeric values from a column. We can alternatively run a separate query to return all values that contain numeric data.

How do I check if a column contains only numbers in SQL?

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


2 Answers

To be safe, forget about ISNUMERIC

If you are not expecting negative numbers, you can use this

INSERT INTO #Temp SELECT ID FROM Table
Where Id > ''  -- is not the empty string and is not null
  AND not ID like '%[^0-9]%'  -- contains digits only
like image 96
RichardTheKiwi Avatar answered Sep 18 '22 06:09

RichardTheKiwi


ISNumeric(Id)=0 should be ISNumeric(Id)=1

However ISNUMERIC has a problem

run this

SELECT ISNUMERIC('2d5'), ISNUMERIC('-'), ISNUMERIC('+')

Those all return 1

Take a look at IsNumeric, IsInt, IsNumber for some ways to figure out if it can be converted to an integer

like image 24
SQLMenace Avatar answered Sep 22 '22 06:09

SQLMenace