1

I am being challenged by SQL Server. I have this simple query

SELET * 
FROM mytable
WHERE ISNUMERIC(propertyvalue) = 1 
  AND CONVERT(int, CONVERT(decimal(9, 0), ISNULL(propertyvalue, 0 ))) > 0 

I tried to change the conversion line from

CONVERT(decimal(9, 0), ISNULL(propertyvalue, 0))

to

CONVERT(decimal(9, 2), ISNULL(propertyvalue, 0))

or

CAST(ISNULL(propertyvalue, 0) AS numeric)

none of what I am trying is working what so ever. I keep getting this error

Msg 8114, Level 16, State 5, Line 1
Error converting data type varchar to numeric.

Any ideas on how to solve this problem?

EDITED

The propertyvalue has the type of varchar(255) and it has data like

2
1.5
2.1
String
1String 456
9
  • Could you give an example of the data that won't convert? Commented Nov 20, 2014 at 21:13
  • propertyvalue - what type is? Commented Nov 20, 2014 at 21:14
  • @jpw This, for instance: ISNUMERIC('1e1') Commented Nov 20, 2014 at 21:14
  • I just updated my question with ansers Commented Nov 20, 2014 at 21:17
  • 1
    Dave Gugg has the correct answer below. In your select statement's where clause, because the ISNUMERIC(...) = 1 and the CONVERT(..) > 0 conditions are on the same level they are both evaluated no matter if the value is numeric or not. The non-numeric values must be filtered first. Commented Nov 20, 2014 at 21:22

2 Answers 2

4

I believe you need to filter out the string data before trying the convert:

 SELECT *
 INTO   #temp
 FROM   mytable
 WHERE  propertyvalue NOT LIKE '%[^0-9]%' 

 SELECT *
 FROM   #temp
 WHERE  CONVERT(INT, CONVERT(DECIMAL(9, 0), ISNULL(propertyvalue, 0))) > 0

 DROP TABLE #temp
Sign up to request clarification or add additional context in comments.

8 Comments

It is not working. I tried to do the conversion in the select as well but that is not working. I get Error converting data type varchar to numeric.
Just because you are using a CTE, it doesn't mean that the results are filtered first. Also, this doesn't take into account values like '1e1', where ISNUMERIC returns 1
Edited to correct Lamak's first objection. As to the ISNUMERIC "bug", I don't have a good way to correct. Suggestions?
The real issue is that ISNUMERIC is "tricked" by values like '1e1'. sqlservercentral.com/Forums/Topic243646-8-1.aspx
another idea is to use TRY_PARSE(propertyvalue as int). And the condition would be WHERE TRY_PARSE(propertyvalue as int) IS NOT NULL.
|
-1

i think it was to do with the period, it doesnt know how to convert it.

have you tried float?

CONVERT(float, ISNULL(propertyvalue, 0 ))

1 Comment

works for me, if you copied your query directly, you have selet and not select

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.