SQL Server: Error converting data type varchar to float - sql

I have the following SELECT statement to calculate RADIANS and COS.
SELECT COS(RADIANS(latitude)) as Lat
FROM tbl_geometry;
But I'm getting an error:
Error converting data type varchar to float.
My attempts:
Attempt #1:
select Cos(convert(float, (Radians(convert(float, latitude))))) as Lat
from tbl_geometry;
Attempt #2.
select Cos(Radians(convert(float, latitude))) as Lat
from tbl_geometry;
Both attempts result in the same error.
Note: column Latitude is of type varchar.

Use try_convert() to find the invalid data:
select latitude
from tbl_geometry
where try_convert(float, latitude) is null;
try_convert() is available in SQL Server 2012+.

You can use:
SELECT CASE
WHEN PATINDEX('%[^0-9]%', latitude) > 0 THEN 0
ELSE Cos(Radians(convert(float,latitude)))
end as latitude
FROM tbl_geometry
You can use the THEN to fill the attribute with null or other values if non-convertable values are encountered. Or you can use the PATINDEX in the WHERE if you want to skip those rows all together. (You may have to play around with the patindex, I don't usually use floats, so I'm not sure what is and isn't allowed. You may want to include decimal points, for example.)

Related

Converting nvarchar to int, converting phone with symbols with only numbers

I am trying to convert phone number from the column 'phone' from the table 'Clients'. I have tried the following syntaxes, but I still get error messages -
1. SELECT CAST(phone as int)
FROM Clients
Error: Conversion failed when converting the nvarchar value '030-3456789' to data type int
2. SELECT CONVERT(int, phone)
FROM Clients
Conversion failed when converting the nvarchar value '030-3456789' to data type int.
3. SELECT CAST(phone AS BIGINT)
FROM Clients
WHERE ISNUMERIC(phone) = 1
The query doesn't return error but there is no result, the column is empty.
It looks (from your example syntax) like you might be using SQL Server.
If that's the case and it's 2017+ you can do the following which copes with any combination of non-numeric values.
Based on your comments the following should work
select Try_Convert(bigint, Replace(Translate('(5) 789-0123','()-',' '),' ',''))
Result: 57890123
If you are using SQL Server 2016 or earlier you have to nest multiple replacements:
select Try_Convert(bigint, Replace(Replace(Replace(Replace('(5) 789-0123)','-',''),'(',''),')',''),' ',''))
Because at least some of your records cannot be covert to numeric by default, as the indicated one 030-3456789
You basically need to replace/eliminate the dash in between:
SELECT cast(replace('12-3', '-', '') as int)
Anyway, welcome to StackOverflow.

How to multiply string value to longint in SQL

I have the below data which I want to multiply together, column A times column B to get column C.
A has datatype string and B has datatype long.
A B
16% 894
15% 200
I have tried this expression in query cast(A as int)*B but it is giving me an error.
You can try below way -
select cast(left(A, patindex('%[^0-9]%', A+'.') - 1) as int)*B
from tablename
You need to remove the '%' symbol before attempting your cast. And assuming you are actually wanting to calculate the percentage, then you also need to divide by 100.00.
cast(replace(A,'%','') as int)/100.00*B
Note: You need to use 100.00 rather than 100 to force decimal arithmetic instead of integer. Or you could cast as decimal(9,2) instead of int - either way ensures you get an accurate result.
You may well want to reduce the number of decimal points returned, in which case cast it back to your desired datatype e.g.
cast(cast(replace(A,'%','') as int)/100.00*# as decimal(9,2))
Note: decimal(9,2) is just an example - you would use whatever precision and scale you need.
The syntax of the cast in SQL Server is CAST(expression AS TYPE);
As you cannot convert '%' to an integer so you have to replace that with an empty character
as below:
SELECT cast(replace(A,'%','') AS int);
Finally you can write as below:
SELECT (cast(replace(A,'%','') AS int)/100.00)*B as C;

Error converting data type varchar to float isnumeric = 1

When I run the script:
select
cast(s as float)
from
t
where
ISNUMERIC(s) = 1
it stops with the error:
Error converting data type varchar to float.
Why does it happen? I'm trying to convert to float only numerics. How do I found out which row causes the error?
The isnumeric function thinks just about everything is a number. Use "try_convert" instead. if the value can't convert to your destination datatype, it returns null.
select convert(float, '1,0,1')
where try_convert(float, '1,0,1') is not null
If you are on an older version of SQL, I would write my own function.
I usually face with this when the value in a column you are trying to convert to float contains a comma (,) as thousand separator:
SELECT ISNUMERIC('140,523.86')
The Result is 1, but unable to cast it as a float.
By replacing it works fine for me:
SELECT
CAST( replace(s,',','') AS float ) AS Result
FROM t
WHERE ISNUMERIC(replace(s,',','')) = 1
ISNUMERIC() function will return 1 for values like 123e3 because these values are Interpreted as numeric values. Because sql server sees this as 123 , 3 to the powers of 10 which is really a numeric value.
You should try something like....
Select *
From tableName
WHERE Col NOT LIKE '%[^0-9]%'
This will return any row where there is a non-numeric character, even values with a ..

sqlserver sum with minus

I use sqlserver 2012.
I have a query like this
SELECT SUM(TH.CLEAVE_EARN_DAY), SUM(TH.CLEAVE_DAY),
SUM(TH.CLEAVE_EARN_DAY) - SUM(TH.CLEAVE_DAY)
FROM TH_LEAVE_CARD TH
The result is 0, 14.5, -15
so -15 is wrong. Must be -14.5
any suggestion ?
This is what you can try
SELECT SUM(TH.CLEAVE_EARN_DAY), SUM(TH.CLEAVE_DAY),
SUM(TH.CLEAVE_EARN_DAY)*1.0 - SUM(TH.CLEAVE_DAY)
FROM TH_LEAVE_CARD TH
Multiplying with 1.0 will just give you back decimal value and taking away will give you what you asked for
Try converting all arguments to the same datatype and then do calculation:
SELECT
SUM(CAST(TH.CLEAVE_EARN_DAY AS DECIMAL(18,2))),
SUM(CAST(TH.CLEAVE_DAY AS DECIMAL(18,2))),
SUM(CAST(TH.CLEAVE_EARN_DAY AS DECIMAL(18,2))
- CAST(TH.CLEAVE_DAY AS DECIMAL(18,2))) AS substraction
FROM TH_LEAVE_CARD TH
Also you can combine:
SUM(TH.CLEAVE_EARN_DAY) - SUM(TH.CLEAVE_DAY)
to (if both column are NOT NULL):
SUM(TH.CLEAVE_EARN_DAY - TH.CLEAVE_DAY)
or (thanks Arvo for pointing this):
SUM(ISNULL(TH.CLEAVE_EARN_DAY,0) - ISNULL(TH.CLEAVE_DAY,0))
To perform mathematical operations on columns:
Used columns should be converted into same numeric/decimal data type.
To handle null values you may use ISNULL function.
Ex:
SELECT SUM(TH.CLEAVE_EARN_DAY), SUM(TH.CLEAVE_DAY),
SUM(cast (TH.CLEAVE_EARN_DAY) as decimal(5,1)) - SUM(cast ( (TH.CLEAVE_DAY) as decimal(5,1))
FROM TH_LEAVE_CARD
There is few reason why the result is not as per what you are expecting. In Sql Server any math operation that contains a null would result to null. for example sum(1,2,3,null,4) is equal to null. 1 + null also equal to null.
therefore it would be safer to use isnull function to assign a default value in case the value is null.
for mathematical operation. sql server would do the calculation based on the specified data type. for example int / int = int. therefore the result would be missled. because most of the time int / int = float.
it would be better to change the value to double prior to do any arithmetic operation.
below is the example after include the isnull function as well as cast to float.
SELECT SUM(CAST(ISNULL(TH.CLEAVE_EARN_DAY,0) as double)), SUM(cast(ISNULL(TH.CLEAVE_DAY,0) as double)),
SUM(cast(ISNULL(TH.CLEAVE_EARN_DAY,0) as double)) - SUM(cast(ISNULL(TH.CLEAVE_DAY,0) as double))
FROM TH_LEAVE_CARD TH

SQL: Unable to CAST a query

SELECT CAST ((SUM(r.SalesVolume)/1000) AS decimal(3,3)) FROM RawData r
The above is a part of a query that I am trying to run but returns an error:
Lookup Error - SQL Server Database Error: Arithmetic overflow error converting int to data type numeric.
Not sure what this means.
The result column looks like(Without dividing by 1000 and casting):
Total_Sales_Volume
64146
69814
68259
56318
66585
51158
44365
49855
49553
88998
102739
55713
Tried casting as float but doesnt help.
The Problem is decimal(3,3) --> this means a number with 3 digit, 3 of them behind the decimal point. If you want a number like this 1234567.123 you would have do declare it as decimal(10,3)
Try this:
SELECT CAST ((SUM(r.SalesVolume)/1000.0) AS decimal(6,3)) FROM RawData r
decimal(3,3) means that you allow numbers with 3 digits in total, and 3 of these are behind the comma ... I think you meant decimal(6,3)
EDIT: In addition, you need to to divide by 1000.0, not by 1000.
If you divide by 1000, it is an integer division.
If you divide by 1000.0, then it becomes a decimal division, with commas.
Try following:
SELECT CAST ((SUM(r.SalesVolume)/1000) AS numeric(6,3)) FROM RawData r