Data type varchar to numeric - sql

I have a table with Varchar values that are numbers, and I want them to be decimal values. I'm getting an error saying Error converting data type varchar to numeric. I've tried:
SELECT ROUND(CAST(MYCOLUMN AS decimal(10, 2)), 2)
FROM TABLE
and
ALTER TABLE MYTABLE
ALTER COLUMN MYCOLUMN DECIMAL(10,2)
and
ALTER TABLE MYTABLE
MODIFY COLUMN ACQ_FIELD_8 DECIMAL(10,2)
and
SELECT ISNULL(CAST(NULLIF(MYCOLUMN, 'NULL') AS NUMERIC(10,2)), 0)
FROM MYTABLE
and I keep getting the same error. I looked the through the data to look for any special characters or letters by using:
SELECT MYCOLUMN FROM MYTABLE
WHERE MYCOLUMN LIKE '%[a-zA-Z]%'
or MYCOLUMN LIKE '%[(]%' --etc for each character.
The only thing that I have found is that every value for some reason has a '^' in it, but when I replace the '6' with nothing, the value still can't be converted to a decimal or numeric. If I try ordering the column by number (< 0.00), I get Arithmetic overflow error converting varchar to data type numeric.
Anyone know what to do?

Try this :
select round(try_convert(decimal(10,2), Mycolumn),2)
looks like you have some values which can not be converted to decimal. try_convert will convert them as NULL

You can try isnumeric:
SELECT ROUND(CAST(MYCOLUMN AS decimal(10, 2)), 2)
FROM TABLE
WHERE isnumeric(MYCOLUMN) = 1

Related

Conversion failed when converting the nvarchar value to data type int - Error Message

My Query
Select * from MyTable
The table consists 300k rows.
It runs for 200k+ rows and this error pops up.
How to handle this to get the full data?
Does MyTable have any computed columns?
Table consists of a computed column with the name IsExceeds which is given below for your reference.
This is the computed column formula:
(CONVERT([int],[Pro_PCT])-CONVERT([int],replace([Max_Off],'%','')))
Field Definitions:
[Pro_PCT] [nvarchar](50) NULL,
[Max_Off] [nvarchar](50) NULL,
[IsExceeds] AS (CONVERT([int],[Pro_PCT])-CONVERT([int],replace([Max_Off],'%','')))
Kindly convert in float then convert into int.
declare #n nvarchar(20)
set #n='11.11'
if (isnumeric(#n)=0)
SELECT 0
else
SELECT CAST(CONVERT(float, #n) as int) AS n
Why are you storing amounts as strings? That is the fundamental problem.
So, I would suggest fixing your data. Something like this:
update mytable
set max_off = replace(max_off, '%');
alter table mytable alter pro_pct numeric(10, 4);
alter table mytable alter max_off numeric(10, 4);
(Without sample data or an example of the data I am just guessing on a reasonable type.)
Then, you can define IsExceeds as:
(Pro_PCT - Max_Off)
Voila! No problems.
Based on the formula - either Pro_PCT or Max_Off contains the value 11.11 (well, with an extra % for Max_Off. Perhaps they also contain other values that can't be converted to int.
Here's what you can do to find all the rows that will cause this problem:
Select *
from MyTable
where try_cast(Pro_PCT as int) is null
or try_cast(replace([Max_Off],'%','') as int) is null
After you've found them, you can either fix the values or change the calculation of the computed column to use try_cast or try_convert instead of convert.
Check the bad data with
select * from MyTable where isnumeric( Max_Off ) = 0

SQL: converting a column of numeric and null values to FLOAT

I have a table with a column of varchar type. The column contains 568710 records of numeric (I mean the ISNUMERIC() returns 1) and 91 records of null values (i.e., the ISNUMERIC() returns 0). Now, I need to convert the column to FLOAT without losing the null records or replacing them with any other value. Is it possible in SQL?
When I use CONVERT(FLOAT, [Value]) conversion, I get the following error:
Msg 8114, Level 16, State 5, Line 48
Error converting data type varchar to float.
I read that the null can be converted to any type. So it should be possible.
You can use this
SELECT CONVERT(float, CASE WHEN ISNUMERIC(columnName) = 1 THEN columnName ELSE NULL END) FROM TableABC
Try :::
ALTER TABLE tablename
ADD NewFloatColumn FLOAT
UPDATE TableName
SET NewFloatColumn =
CASE WHEN ISNUMERIC(VarcharColumn) =1 THEN CAST (VarcharColumn AS float)
WHEN UPPER(VarcharColumn) = 'NULL' THEN null
END
Select (CASE WHEN ISNUMERIC(c) = 1
THEN (CASE WHEN c LIKE '%.%' THEN c ELSE c + '.00' END)
ELSE '0.00'
END)from table_name
I just spent some time scratching my head at the same problem. I was able to resolve this by converting first to int, then to float. Testing shows no data loss as my float column did not contain decimal, it simply had to match the dtype of another column for a later UNION operation.
This was completed on SQL Server 2016.
ALTER TABLE table1
ALTER COLUMN column1 int;
ALTER TABLE table1
ALTER COLUMN column1 float;

SQL - How to change data type float to nvarchar and remove scientific notation

How do I change the data type float to nvarchar in order to remove the scientific notation and still keep precision? Consider the following:
CREATE TABLE ConversionDataType (ColumnData FLOAT);
INSERT INTO ConversionDataType VALUES (25566685456126);
INSERT INTO ConversionDataType VALUES (12345545546845);
INSERT INTO ConversionDataType VALUES (12345545545257);
When I do a simple read I get the following data, as expected:
select * from ConversionDataType
ColumnData
------------------------------------
25566685456126
12345545546845
12345545545257
Now when I try update the data type to an nvarchar, it gets stored in scientific notation which is something I don't want:
update ConversionDataType
set ColumnData = CAST(ColumnData AS NVARCHAR)
The result set is as follows:
25566700000000
12345500000000
12345500000000
It replaces some digits and adds zeros after the 6th index. How can I go about this? I had a look at the Convert function but that is only for converting date time data types.
Being valid what others said in comment, if you just want to convert float to varchar without scientific notation, you need to convert to numeric. You can try this:
SELECT CAST(CAST(CAST(25566685456126291 AS FLOAT) AS NUMERIC) AS NVARCHAR)
Output:
C1
------------------------------
25566685456126292
Whereas
SELECT CAST(CAST(25566685456126291 AS FLOAT) AS NVARCHAR) AS C1
gives:
C1
------------------------------
2.55667e+016
If you need to change datatype, I think you should add a new column, update it and (if you want) delete the old column and rename the new column at the end.
CREATE TABLE TEST1 (C1 FLOAT)
INSERT INTO TEST1 VALUES (25566685456126291);
ALTER TABLE TEST1 ADD C2 VARCHAR(18)
UPDATE TEST1 SET C2=CAST(CAST(C1 AS NUMERIC) AS VARCHAR)
SELECT * FROM TEST1
Output:
C1 C2
---------------------- ------------------
2.55666854561263E+16 25566685456126292
FLOAT was a very bad decision as this is not a precise data type. If you wanted to store the phone numbers as numbers, you'd have to go for DECIMAL instead.
But you'll have to use NVARCHAR instead. And this is the only reasonable design, as phone numbers can have leading zeros or start with a plus sign. So the first thing is to introduce an NVARCHAR column:
ALTER TABLE ConversionDataType ADD ColumnDataNew NVARCHAR(30);
The function to convert a number into a string in SQL Server is FORMAT. It lets you state the format you want to use for the conversion, which is integer in your case (a simple '0'):
update ConversionDataType set ColumnDataNew = format(ColumnData, '0');
At last remove the old column and then rename the new one with the same name. SQL Server lacks an ALTER TABLE syntax to rename a column, so we must call sp_RENAME instead (at least this is what I have read on the Internet; here is a link to the docs: https://msdn.microsoft.com/de-de/library/ms188351.aspx).
ALTER TABLE ConversionDataType DROP COLUMN ColumnData;
EXEC sp_RENAME 'ConversionDataType.ColumnDataNew', 'ColumnData', 'COLUMN';
Here you can see the results: http://rextester.com/GLLB27702
SELECT CONVERT(NVARCHAR(250), StudentID) FROM TableA
StudentID is your Float Column of database
or Simply use
SELECT CONVERT(NVARCHAR(250), yourFloatVariable)

sql server conversion failed

I am querying a database in which I am getting the following exception:
Conversion failed when converting varchar value 'B6UJ978023EC' to data type int
How can I fix it?
My guess is that your query looks something like this:
select * from mytable where SomeField = 'B6UJ978023EC'
If that's the case, SomeField was declared as an INT datatype and Sql Server is attempting to convert 'B6UJ978023EC' to an INT which won't work.
It's possible that you're trying to do an insert/update, so this wouldn't work either if SomeField is an INT.
update mytable
set SomeField = 'B6UJ978023EC'
where something = something
insert mytable (field1, field2, SomeField)
values(123, 'abc', 'B6UJ978023EC')
Same result, Conversion failed when converting varchar value 'B6UJ978023EC' to data type int
In this case, either change the datatype of the column, or change the value of the variable.
Update:
If your column's datatype is (N)VARCHAR but contains some real numbers, then you can simply add single quotes around the number you're looking for.
-- works
select * from mytable where SomeField = '123456'
-- doesn't work - same error
select * from mytable where SomeField = 123456
try this:
Error is because you are trying to convert a character value to integer value. Just add the below condition to the query so that it will select only integer values
where ISNUMERIC(col+ '.0e0')=1

Convert nvarchar to bigint in Sql server 2008

I want insert all rows of a table into another table, and I also want convert a nvarchar field into bigint, but when I use convert(bigint, col1) SQL Server shows an error:
Error converting data type nvarchar
to bigint
How can I fix this problem?
You could try to use ISNUMERIC to determine those rows that are indeed numeric:
UPDATE dbo.YourTable
SET BigIntColumn = CAST(NVarcharColumn AS BIGINT)
WHERE ISNUMERIC(NVarcharColumn) = 1
That would convert those rows that can be converted - the others need to be dealt with manually.
You should convert bigint to nvarchar not vice versa
cast(Other_Column_name as nvarchar) not cast (Column_Name as bigint)
you can try this:
CAST(CAST(col1 as NUMERIC) as BIGINT)
Here I convert navrchar value of column into bigInt and than perform Addition of thos two columns find blow :
SELECT (CAST(col1 AS BIGINT) + CAST(col2 AS BIGINT)) AS TotalValue from tableName