I also received the message «Error converting data type nvarchar to float». This was from a query in SQL Server Management Studio (SSMS) from SQL Server 2019.
In my case there were undecipherable characters in the source data, which was exported to CSV from Excel. Some columns were in the «Accounting» format, which has spaces, currency symbols, commas, and parenthesis, like this:
- positive values: $ 123,456.78
- negative values: $(123,456.78)
To account for this and resolve the error, I simply inserted a nested REPLACE()
function to remove some characters and replace others, and wrapped it with IsNull()
to return zero when necessary.
First I will describe:
- replace any
$
,
)
with nothing (aka null string or empty quotes''
) - replace any
(
with-
(aka hyphen or negative symbol)
And here is the SQL:
Original:
CONVERT(float, exp_TotalAmount)
Replacement:
CONVERT(float, IsNull(REPLACE(REPLACE(REPLACE(REPLACE(exp_TotalAmount,'(','-'),')',''),',',''),'$',''),0))
Here broken up for easier read, innermost first:
REPLACE(exp_TotalAmount, '(', '-')
REPLACE(X, ')', '')
REPLACE(X, ',', '')
REPLACE(X, '$', '')
IsNull (X, 0)
CONVERT(float, X)
This works for me?
DECLARE @tbl TABLE(test NVARCHAR(100));
INSERT INTO @tbl VALUES
('1248')
,('1248')
,('193.79')
,('201.56')
,('1475.71')
,('97.86')
,('97.86')
,('97.86')
,('125.49')
,('97.86')
,('447.83')
,('450')
,('492.99')
,('450');
SELECT *
,CAST(test AS FLOAT) AS CastedValue
FROM @tbl;
But the main question is: Why?
Hint 1: Float is the wrong type for this!
From the column name I take, that you are dealing with costs. The FLOAT
type is absolutely to be avoided here! You should use DECIMAL
or specialised types to cover money or currency values…
Hint 2: NVarchar is the wrong type for this!
And the next question is again: Why? Why are these values stored as NVARCHAR
? If ever possible you should solve your problem here…
UPDATE
You edited your question and added this
insert into B () select[DestAddress], [COST]
I do not know the target table’s column names, but this should work
INSERT INTO B(ColumnForAddress,ColumnForCost)
SELECT CAST([COST] AS FLOAT),[DestAddress] FROM YourSourceTable
UPDATE 2
After all your comments I’m pretty sure, that there are invalid values within your numbers list. Use ISNUMERIC
or — if you are using SQL-Server-2012+ even better TRY_CAST
to find invalid values.
- Remove From My Forums
-
Question
-
Hi all—
I’ve been trying to run the program below and I keep on getting the error «Error converting data type nvarchar to float»
SELECT
distinct
coalesce(a.File_NBR,b.File_NBR)as ID,
b.Division,
b.Program,
a.Full_Name,
a.SBC_RESULT
FROM New_EEs.dbo.vw_SBC_RESULTS a
full join New_EEs.dbo.vw_SBC_Employee_Info b
on a.File_NBR=b.File_NBR
where (a.File_NBR is not null OR b.File_NBR is not null)
and A.Full_Name is not null
order by a.Full_Name, b.Division, b.ProgramWhen I comment out /***and A.Full_Name is not null ***/ the program works.
I can’t figure out what the error means and why the join works when I comment out /***and A.Full_Name is not null ***/
Any feedback is appreciated.
Thanks!
Всем доброго времени суток!
На сервере есть табличная функция
SQL | ||
|
Если ее вызвать на сервере то она успешно отработает если же на стороне клиент то вылезет ошибка «Ошибка при преобразовании типа данных nvarchar к float»
На клиенте есть класс
C# | ||
|
и функция
C# | ||
|
Собствено вопрос почему? Великий гугл ответа не дал
Добавлено через 36 минут
Проблема решилась я дебил. Если кому будет интересен ответ то вот он
SQL | ||
|
Sometimes, under certain circumstances, when you develop in SQL Server and especially when you try to convert a string data type value to a float data type value, you might get the error message: error converting data type varchar to float. As the error message describes, there is a conversion error and this is most probably due to the input parameter value you used in the conversion function.
Read more below on how you can easily resolve this problem.
Reproducing the Data Type Conversion Error
As mentioned above, the actual reason you get this error message, is that you are passing as a parameter to the CAST or CONVERT SQL Server functions, a value (varchar expression) that is invalid and cannot be converted to the desired data type.
Consider the following example:
----------------------------------------- --Variable declaration and initialization ----------------------------------------- DECLARE @value AS VARCHAR(50); SET @value = '12.340.111,91'; --Perform the casting SELECT CAST(@value AS FLOAT); --or --Perform the conversion SELECT CONVERT(FLOAT, @value); -----------------------------------------
If you execute the above code you will get an error message in the following type:
Msg 8114, Level 16, State 5, Line 6
Error converting data type varchar to float.
Another similar example where you get the same data type conversion error, is the below:
----------------------------------------- --Variable declaration and initialization ----------------------------------------- DECLARE @value2 AS VARCHAR(50); SET @value2 = '12,340.15'; --Perform the casting SELECT CAST(@value2 AS FLOAT); --or --Perform the conversion SELECT CONVERT(FLOAT, @value2);
Why you get this Conversion Error
The exact reason for getting the error message in this case is that you are using the comma (,) as a decimal point and also the dots as group digit symbols. Though SQL Server considers as a decimal point the dot (.). Also when converting a varchar to float you must not use any digit grouping symbols.
Strengthen your SQL Server Administration Skills – Enroll to our Online Course!
Check our online course on Udemy titled “Essential SQL Server Administration Tips”
(special limited-time discount included in link).Via the course, you will learn essential hands-on SQL Server Administration tips on SQL Server maintenance, security, performance, integration, error handling and more. Many live demonstrations and downloadable resources included!
(Lifetime Access/ Live Demos / Downloadable Resources and more!) Enroll from $12.99
How to Resolve the Conversion Issue
In order for the above code to execute, you would need to first remove the dots (that is the digit grouping symbols in this case) and then replace the comma with a dot thus properly defining the decimal symbol for the varchar expression.
Note: You need to be careful at this point, in order to correctly specify the decimal symbol at the correct position of the number.
Therefore, you can modify the code of example 1 as per below example:
------------------------------------------- --Variable declaration and initialization ------------------------------------------- DECLARE @value AS VARCHAR(50); SET @value = '12.340.111,91'; --Prepare the string for casting/conversion to float SET @value = REPLACE(@value, '.', ''); SET @value = REPLACE(@value, ',', '.'); --Perform the casting SELECT CAST(@value AS FLOAT); --or --Perform the conversion SELECT CONVERT(FLOAT, @value); -----------------------------------------
If you execute the above code you will be able to get the string successfully converted to float.
Similarly, you can modify the code of example 2 as per below example:
----------------------------------------- --Variable declaration and initialization ----------------------------------------- DECLARE @value2 AS VARCHAR(50); SET @value2 = '12,340.15'; --Prepare the string for casting/conversion to float SET @value2 = REPLACE(@value2, ',', ''); --Perform the casting SELECT CAST(@value2 AS FLOAT); --or --Perform the conversion SELECT CONVERT(FLOAT, @value2);
Again, if you execute the above code you will be able to get the string successfully converted to float.
*Note: Even though you can try changing the regional settings of the PC for setting the dot (.) as the decimal symbol, this will only affect the way the data is presented to you when returned from the casting/conversion call. Therefore, you still have to modify the varchar expression prior to the casting/conversion operation.
Regarding the message: error converting data type varchar to numeric
The above error message is similar to the one we examined in this article, therefore, the way for resolving the issue is similar to the one we described in the article. The only different for the numeric case, is that you will have to replace FLOAT with numeric[ (p[ ,s] )]. Learn more about the numeric data type in SQL Server and how to resolve the above conversion issue, by reading the relevant article on SQLNetHub.
Watch the Live Demonstration on the VARCHAR to FLOAT Data Type Conversion Error
Learn essential SQL Server development tips! Enroll to our Online Course!
Check our online course titled “Essential SQL Server Development Tips for SQL Developers”
(special limited-time discount included in link).Sharpen your SQL Server database programming skills via a large set of tips on T-SQL and database development techniques. The course, among other, features over than 30 live demonstrations!
(Lifetime Access, Certificate of Completion, downloadable resources and more!) Enroll from $12.99
Featured Online Courses:
- SQL Server 2022: What’s New – New and Enhanced Features
- Introduction to Azure Database for MySQL
- Working with Python on Windows and SQL Server Databases
- Boost SQL Server Database Performance with In-Memory OLTP
- Introduction to Azure SQL Database for Beginners
- Essential SQL Server Administration Tips
- SQL Server Fundamentals – SQL Database for Beginners
- Essential SQL Server Development Tips for SQL Developers
- Introduction to Computer Programming for Beginners
- .NET Programming for Beginners – Windows Forms with C#
- SQL Server 2019: What’s New – New and Enhanced Features
- Entity Framework: Getting Started – Complete Beginners Guide
- A Guide on How to Start and Monetize a Successful Blog
- Data Management for Beginners – Main Principles
Read Also:
- Advanced SQL Server Features and Techniques for Experienced DBAs
- SQL Server Database Backup and Recovery Guide
- The Database Engine system data directory in the registry is not valid
- Rule “Setup account privileges” failed – How to Resolve
- Useful Python Programming Tips
- SQL Server 2022: What’s New – New and Enhanced Features (Course Preview)
- How to Connect to SQL Server Databases from a Python Program
- Working with Python on Windows and SQL Server Databases (Course Preview)
- The multi-part identifier … could not be bound
- Where are temporary tables stored in SQL Server?
- How to Patch a SQL Server Failover Cluster
- Operating System Error 170 (Requested Resource is in use)
- Installing SQL Server 2016 on Windows Server 2012 R2: Rule KB2919355 failed
- The operation failed because either the specified cluster node is not the owner of the group, or the node is not a possible owner of the group
- A connection was successfully established with the server, but then an error occurred during the login process.
- SQL Server 2008 R2 Service Pack Installation Fails – Element not found. (Exception from HRESULT: 0x80070490)
- There is insufficient system memory in resource pool ‘internal’ to run this query.
- Argument data type ntext is invalid for argument …
- Fix: VS Shell Installation has Failed with Exit Code 1638
- Essential SQL Server Development Tips for SQL Developers
- Introduction to Azure Database for MySQL (Course Preview)
- [Resolved] Operand type clash: int is incompatible with uniqueidentifier
- The OLE DB provider “Microsoft.ACE.OLEDB.12.0” has not been registered – How to Resolve it
- SQL Server replication requires the actual server name to make a connection to the server – How to Resolve it
- Issue Adding Node to a SQL Server Failover Cluster – Greyed Out Service Account – How to Resolve
- Data Management for Beginners – Main Principles (Course Preview)
- Resolve SQL Server CTE Error – Incorrect syntax near ‘)’.
- SQL Server is Terminating Because of Fatal Exception 80000003 – How to Troubleshoot
- An existing History Table cannot be specified with LEDGER=ON – How to Resolve
- … more SQL Server troubleshooting articles
Recommended Software Tools
Snippets Generator: Create and modify T-SQL snippets for use in SQL Management Studio, fast, easy and efficiently.
Learn more
Dynamic SQL Generator: Convert static T-SQL code to dynamic and vice versa, easily and fast.
Learn more
Get Started with Programming Fast and Easy – Enroll to the Online Course!
Check our online course “Introduction to Computer Programming for Beginners”
(special limited-time discount included in link).
(Lifetime Access, Q&A, Certificate of Completion, downloadable resources and more!) Learn the philosophy and main principles of Computer Programming and get introduced to C, C++, C#, Python, Java and SQL.
Enroll from $12.99
Subscribe to our newsletter and stay up to date!
Subscribe to our YouTube channel (SQLNetHub TV)
Easily generate snippets with Snippets Generator!
Secure your databases using DBA Security Advisor!
Generate dynamic T-SQL scripts with Dynamic SQL Generator!
Check our latest software releases!
Check our eBooks!
Rate this article: (17 votes, average: 5.00 out of 5)
Loading…
Reference: SQLNetHub.com (https://www.sqlnethub.com)
How to resolve the error: Error converting data type varchar to float
Click to Tweet
Artemakis Artemiou is a Senior SQL Server Architect, Author, a 9 Times Microsoft Data Platform MVP (2009-2018). He has over 20 years of experience in the IT industry in various roles. Artemakis is the founder of SQLNetHub and {essentialDevTips.com}. Artemakis is the creator of the well-known software tools Snippets Generator and DBA Security Advisor. Also, he is the author of many eBooks on SQL Server. Artemakis currently serves as the President of the Cyprus .NET User Group (CDNUG) and the International .NET Association Country Leader for Cyprus (INETA). Moreover, Artemakis teaches on Udemy, you can check his courses here.
Views: 30,694