Click here to Skip to main content
15,912,205 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,

I want to choose nearest lower and upper values from table for that I am using below query
SQL
DECLARE @lat1 decimal(18,6)
DECLARE @lon1 decimal(18,6)

SET @lat1 = 17.43969
SET @lon1 = 78.4842

SELECT TOP 5 ID, Cl_Name,lat1,lon1 
from MyTable
ORDER BY ABS(cast(lat1 as decimal(18,6)) - @lat1)

If I run above query, it gives me below error-
Error converting data type nvarchar to numeric.


What is wrong in this query
Posted
Updated 19-Jul-14 0:37am
v5
Comments
CHill60 15-Jul-14 8:13am    
What is your table definition (just ID, Cl_Name, lat1 and lon1)
[no name] 15-Jul-14 8:20am    
No table contains - address, contact number,name and other columns
I want closest match value to lat1, lon1
CHill60 15-Jul-14 8:39am    
I actually meant that I needed to see the datatypes. See the solution from OriginalGriff
[no name] 19-Jul-14 6:55am    
Well you get that error for that exact same reason that you have already been told. And, TOP 5 is not the same as MIN and MAX.

Why are you casting your database value to a string, in order to try and take the absolute value of it? If it's numeric already, then it's a pointless waste of time - since it has to be converted back to a number again in order for ABS to work.
And if it's a string, then it does nothing useful either.

I'm guessing that you lat1 column contains string data, and that it contains characters that SQL isn't expecting as part of a number. If so, then you need to change your DB and store numeric values as numbers...or this problem will recur on a regular basis.
 
Share this answer
 
Comments
[no name] 16-Jul-14 1:00am    
Ok thank you for reply.

That database is created 3-4 years back and "lat1" column datatype is - nvarchar(50) so i am converting it to numeric.

Change of datatype does not allowed in table.[And also if i will add diff column then i have to change all stored procedures.]
Other than that there is no option?
If this query was working well and now started getting fail then it seems that you have bad data in Lat1 column. You can identify these bad rows using following query. Once data gets corrected your own query will run fine.

SQL
SELECT ID, Cl_Name,lat1,lon1
FROM MyTable
WHERE ISNUMERIC(lat1) <> 1;
 
Share this answer
 
Hi Prajakta,
Do like below code.

SQL
DECLARE @lat1 decimal(18,6)
DECLARE @lon1 decimal(18,6)

SET @lat1 = 17.43969
SET @lon1 = 78.4842

SELECT TOP 5 ID, Cl_Name,@lat1,@lon1
from MyTable
ORDER BY ABS(cast(@lat1  as decimal(18,6)) - @lat1)


[Edit] By :Nirav Prabtani
Set language code block
[/Edit]
 
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