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?
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.
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.
You can take use advantage of ISNUMERIC() function in SQL Server .
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.
Try this:
SELECT * FROM Table WHERE Name LIKE '[0-9]%%'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With