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!
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!
Featured Online Courses:
- SQL Server Security Best Practices
- AI Demystified: A 1-Hour Beginner’s Guide (Suitable for Non-Technical People)
- AI Essentials: A Beginner’s Guide to Artificial Intelligence
- Human-AI Synergy: Teams and Collaborative Intelligence
- SQL Server 2022: What’s New – New and Enhanced Features
- Working with Python on Windows and SQL Server Databases
- Introduction to Azure Database for MySQL
- 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
- Data Management for Beginners – Main Principles
- A Guide on How to Start and Monetize a Successful Blog
Read Also:
- Mastering SQL Server Performance Tuning: Essential Tips and Techniques
- 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
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).Learn the philosophy and main principles of Computer Programming and get introduced to C, C++, C#, Python, Java and SQL.
Subscribe to the GnoelixiAI Hub newsletter on LinkedIn and stay up to date with the latest AI news and trends.
Subscribe to the SQLNetHub YouTube channel (SQLNetHub TV).
Subscribe to my personal YouTube channel.
Rate this article:
Reference: SQLNetHub.com (https://www.sqlnethub.com)
© SQLNetHub
Artemakis Artemiou is a seasoned Senior Database and AI/Automation Architect with over 20 years of expertise in the IT industry. As a Certified Database, Cloud, and AI professional, he has been recognized as a thought leader, earning the prestigious Microsoft Data Platform MVP title for nine consecutive years (2009-2018). Driven by a passion for simplifying complex topics, Artemakis shares his expertise through articles, online courses, and speaking engagements. He empowers professionals around the globe to excel in Databases, Cloud, AI, Automation, and Software Development. Committed to innovation and education, Artemakis strives to make technology accessible and impactful for everyone.
I need to convert nvarchar datatype of my table column to float
But during this operation
the below error message returned by the sql server 2005
'tbl_user_mast' table – Unable to modify table. Error converting data type nvarchar to float.
Hi Shanthi,
Can you post the code which causes this error message to be generated?
This comment has been removed by the author.
Hi )
Can you help a beginner with StoredProcedure? )
I have a table with columns (type varchar) as example:
D1-D2-D3
3 – б –
2 – – 8
1 – –
I need to get the sum of each column
if only there were numbers – then everything is OK
write
…
SELECT
SUM (CAST (Round (D1, 2) As decimal (5,2))) As D1
FROM
…
but i have a letters in some columns, so can't convert string to float
(if in columns is a letter,then SUM is equivalent to = 8 )
so i try to use CASE
…
SELECT
SumD2 =
CASE D2
WHEN 'б' then 8
ELSE
SUM (CAST (Round (D2, 2) As decimal (5,2)))
END
FROM
…
and here's a "gift" – Column dbo.Zadanie.D2 is invalid in the select list because it is not contained in either an aggregate function or ORDER BY clause
tell my what am I doing wrong?
Hi Elena,
You are getting this error because you are using an aggregate (SUM) in the one part of the CASE statement and you are not using an aggregate in the other part.
You could use a GROUP BY or an ORDER BY clause but you would not get the result you expect.
It is difficult to implement the requested logic with a single T-SQL statement because queries read record-by-record the contents of a table. Whenever a character occurs you would need to stop the aggregation and set the sum to 8.
Though, by the time you are using a stored procedure as you said, you can use multiple statements for implementing the required logic.
To this end I would suggest trying the following code in the stored procedure you are building:
DECLARE @d1 AS INT
DECLARE @d2 AS INT
DECLARE @d3 AS INT
DECLARE @sumd1 AS FLOAT
DECLARE @sumd2 AS FLOAT
DECLARE @sumd3 AS FLOAT
SET @d1=(SELECT COUNT(*)
FROM testtable
WHERE Isnumeric(d1) = 0
AND d1 IS NOT NULL)
SET @d2=(SELECT COUNT(*)
FROM testtable
WHERE Isnumeric(d2) = 0
AND d2 IS NOT NULL)
SET @d3=(SELECT COUNT(*)
FROM testtable
WHERE Isnumeric(d3) = 0
AND d3 IS NOT NULL)
IF @d1 = 0
SET @sumd1=(SELECT SUM(CAST(Round (d1, 2) AS DECIMAL (5, 2)))
FROM testtable)
ELSE
SET @sumd1=8
SELECT @sumd1
IF @d2 = 0
SET @sumd2=(SELECT SUM(CAST(Round (d2, 2) AS DECIMAL (5, 2)))
FROM testtable)
ELSE
SET @sumd2=8
SELECT @sumd2
IF @d3 = 0
SET @sumd3=(SELECT SUM(CAST(Round (d3, 2) AS DECIMAL (5, 2)))
FROM testtable)
ELSE
SET @sumd3=8
SELECT @sumd3
If the table contained an ID column along with the value columns maybe another logic could be implemented but by the time the table contains only value columns the above is the workaround I would suggest.
Cheers,
Artemis
Thank you for your quick and detailed response so)
I did so:
SELECT
SUM(CASE D1 WHEN 'б' THEN 8 WHEN 'о' THEN 8 WHEN 'от' THEN 8 WHEN 'к' THEN 8 ELSE CAST(ROUND(D1,2) AS DECIMAL(5,2)) END) as SumD1,
SUM(CASE D2 WHEN 'б' THEN 8 WHEN 'о' THEN 8 WHEN 'от' THEN 8 WHEN 'к' THEN 8 ELSE CAST(ROUND(D2,2) AS DECIMAL(5,2)) END) as SumD2,
SUM(CASE D3 WHEN 'б' THEN 8 WHEN 'о' THEN 8 WHEN 'от' THEN 8 WHEN 'к' THEN 8 ELSE CAST(ROUND(D3,2) AS DECIMAL(5,2)) END) as SumD3,
FROM dbo.PrZad
WHERE (StaffID = @StaffId) AND (MONTH(PlanDataOtch) = @Месяц) AND (YEAR(PlanDataOtch) = @Год) AND (CodZak <> 24)
It works!
Thank you!!
You are welcome! I am glad I helped you!
I also incurred same error msg "Error converting data type nvarchar to numeric", solved converting numeric column to varchar
Problem: TableA.EmpID = TableB.EmployeeID
Here TableA.EmpID is varchar datatype and in other end TableB.EmployeeID was in Decimal datatype. I converted TableB.EmployeeID to varchar datatype.
Solution: TableA.EmpID = Cast (TableB.EmployeeID as Varchar)
So many years after and this function saved my day, month, year, life.. Thanks!
Hi Victor,
I am really glad I helped!
Cheers!