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?
No, you can't use LIKE for numeric fields. Try using < , > or = , >= , <= ;) If you want to search in a numeric field for things like "beginning with 12" or sth like this, your design not fits your needs.
The LIKE operator is used in a WHERE clause to search for a specified pattern in a column. There are two wildcards often used in conjunction with the LIKE operator: The percent sign (%) represents zero, one, or multiple characters. The underscore sign (_) represents one, single character.
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
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
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