Click here to Skip to main content
15,881,380 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello ,
i have a table test in this a column name 'observation_value_numerical' datatype is varchar(10). I want to write query


SQL
SELECT top 4 CONVERT(float, observation_value_numerical),convert(float,'9.0'),* FROM LAB_OBSERVATION where cast (observation_value_numerical as float)>9



But it showing error converting data type varchar to float. in sql server 2008

Table structure is
observation_value_numerical
11.4
5.7
9.2
7.7

how to resolve this error


thanks
Srishti
Posted
Comments
ChauhanAjay 25-Aug-14 5:55am    
just try the below query
SELECT top 4 cast(observation_value_numerical as float),cast('9.0' as float),* FROM LAB_OBSERVATION where cast(observation_value_numerical as float)>9.0

The most obvious is: don't store it as a string at all.
Somewhere in your table there is a value which contains something other that digits and a decimal point, or the locale for the server is set to a culture that doesn't use '.' as a decimal separator.

Change the table so that you store the data as float values: then all you unpleasant-to-read code disappears, and the problem does as well.

Never store items as strings unless they are strings: store dates as DateTime values, store numbers as Integers, or floats. It may seem like a little more work, but it saves a lot of hassle an trouble later - as you are starting to see here.
 
Share this answer
 
Comments
srishti_ 25-Aug-14 6:07am    
i cant change my table structure thanks
OriginalGriff 25-Aug-14 6:16am    
Why not?
If you don't, then you can expect this kind of problem to crop up again, and again, and again - and it will be your app that is blamed, not the DB design, or the person who input the (wrong) data.
ChauhanAjay 25-Aug-14 6:47am    
You can create a backup of the old table and then create a new structure and get the data from the backup table.
OriginalGriff 25-Aug-14 6:57am    
You don't really need to: if he fixes the invalid entries, SQL will let him just change the column type to float, and will convert all the values for him.
Try this:
SQL
SELECT top 4 CONVERT(float, observation_value_numerical),
convert(float,'9.0'),* FROM LAB_OBSERVATION
where CONVERT(float, observation_value_numerical)> 9
 
Share this answer
 
v3
Use
SQL
CASE WHEN ISNUMERIC(observation_value_numerical) THEN CONVERT(float, observation_value_numerical)

to convert varchar to float.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900