Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select only integers from char column using SQL Server

How can I write a select statement to select only integers (and nothing more) from a char column in SQL Server. For example, my table name is POWDER with 2 columns, ID (int) and Name(char (5))

ID     Name
-- ----------
1     AXF22
2     HYWWW
3     24680
4     8YUH8
5     96635

I want to be able to select only those rows that contain an integer and nothing more (ID 3 and ID 5 in this example)

If I try:

SELECT * 
  FROM POWDER
 WHERE Name LIKE '[0-9]%'

...it will return:

ID     Name
--    ----------
3      24680
4      8YUH8
5      96635

Any ideas how to get the rows containing just integers?

like image 365
Andy Select Avatar asked Oct 23 '09 05:10

Andy Select


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 select just the value of an integer in SQL?

Syntax to check if the value is an integer. select yourColumnName from yourTableName where yourColumnName REGEXP '^-?[0-9]+$'; The query wherein we have used regular expression. This will output only the integer value.

How do I select numeric values from an alphanumeric column in SQL?

You can take use advantage of ISNUMERIC() function in SQL Server .


2 Answers

SELECT * FROM POWDER WHERE IsNumeric(Name) = 1

IsNumeric returns 1 for some other characters that are valid in numbers, such as + and - and $ but for your input you should be fine.

like image 65
Chris Latta Avatar answered Nov 15 '22 07:11

Chris Latta


Try this:

SELECT * FROM Table WHERE Name LIKE '[0-9]%%'

like image 23
Ilja Avatar answered Nov 15 '22 06:11

Ilja