views:

182

answers:

3

This is I think a simple problem but not getting the solution yet. I would like to get the valid numbers only from a column as explained here.

Lets say we have a varchar column with following values

ABC
Italy
Apple
234.62
2:234:43:22
France
6435.23
2
Lions

Here the problem is to select numbers only

select * from tbl where answer like '%[0-9]%' would have done it but it returns

    234.62
    2:234:43:22
    6435.23
    2

Here, obviously, 2:234:43:22 is not desired as it is not valid number.

The desired result is

        234.62
        6435.23
        2

Is there a way to do this?

+4  A: 

You can try this

ISNUMERIC (Transact-SQL)

ISNUMERIC returns 1 when the input expression evaluates to a valid numeric data type; otherwise it returns 0.

DECLARE @Table TABLE(
        Col VARCHAR(50)
)

INSERT INTO @Table SELECT 'ABC' 
INSERT INTO @Table SELECT 'Italy' 
INSERT INTO @Table SELECT 'Apple' 
INSERT INTO @Table SELECT '234.62' 
INSERT INTO @Table SELECT '2:234:43:22' 
INSERT INTO @Table SELECT 'France' 
INSERT INTO @Table SELECT '6435.23'
INSERT INTO @Table SELECT '2' 
INSERT INTO @Table SELECT 'Lions'

SELECT  *
FROM    @Table
WHERE   ISNUMERIC(Col) = 1
astander
Thanks a lot for the answer worked just as Intended.
Thunder
+1 This is a far better solution than mine. I'll leave mine, since it appears to work on this limited case but just goes to show I need to learn all the inbuilt functions.
David Hall
Sure David Same here (need to learn inbuilt functions) :) ! Your answer with like is also fine one
Thunder
Unfortunately, ISNUMERIC will accept singletons of + - .
gbn
+1  A: 

Try something like this - it works for the cases you have mentioned.

select * from tbl
where answer like '%[0-9]%'
and answer not like '%[:]%'
and answer not like '%[A-Z]%'
David Hall
+2  A: 

You can use the following to only include valid characters:

SQL

SELECT * FROM @Table
WHERE Col NOT LIKE '%[^0-9.]%'

Results

Col
---------
234.62
6435.23
2
beach
+1 the best solution
gbn