Ms sql error converting data type nvarchar to float

There are two things that need to be fixed.

There are two things that need to be fixed. 

First, you need a test that can be used in SQL 2008R2 to determine if a number can be converted to a float.  A test that should work for you is to combine IsNumeric() with a regular expression that ensures that the string contains only characters that
are valid to be converted to a float.  So the following will test if the columns SQLVal and AccessVal can be converted to floats without error.

WHERE ISNUMERIC(SQLVal) = 1 AND SQLVal NOT LIKE '%[^0-9ED.+-]%' 
  AND ISNUMERIC(AccessVal) = 1 AND AccessVal NOT LIKE '%[^0-9ED.+-]%'

But your second problem is that SQL can process the query in any order it chooses.  So even if your WHERE clause only chooses rows that can be converted to float, SQL might convert ALL of the rows to float and only later check the WHERE clause 
and throw away the rows that don’t match the WHERE clause.  Of course, in your case, if SQL does this, you geet a conversion error before the WHERE clause is processed and the statement fails. 

There are two ways you can fix this, one of which leaves this as a single query, but will make your query longer and  more complex, the other will split your query into two queries.  That way might make your query less efficient depending on what
your are doing (although, in this case, I don’t think that will be a problem).

In the first way, you would change the WHERE clause of the query as above, and the everywhere where you do a convert you would add a CASE statement that makes sure you do not attempt to convert an invalid value.  So, for example, in your SELECT clause,
instead of

,ROUND(ABS(CONVERT(float, AccessVal,1)),0) as AccessFloat

you would use

,CASE WHEN ISNUMERIC(AccessVal) = 1 AND AccessVal NOT LIKE '%[^0-9ED.+-]%' 
   THEN ROUND(ABS(CONVERT(float, AccessVal,1)),0) END As AccessFloat

To be totally safe, you would need to make this change to add the CASE everywhere in your query where you have a CONVERT to float.

The second way would be to Create a temp table or table variable with one column named QA_AutoID.  Then insert into that table only rows which have valid floats in the columns.  Then use that temp table or variable in your query.  Since that
is now two SQL statements, the WHERE selecting only valid floats in the first query will always be done before any converts in the second query.  That would look something like

DECLARE @MyQA Table(QA_AutoID int /* or whatever the correct datatype is */);
INSERT @MyQA(QA_AutoID)
SELECT TOP 1 QA_AutoID 
	FROM QA 
	WHERE ISNUMERIC(SQLVal) = 1 AND SQLVal Not Like '%[^0-9ED.+-]%' 
          AND ISNUMERIC(AccessVal) = 1 AND AccessVal Not Like '%[^0-9ED.+-]%'


SELECT QA_AutoID, AccessVal, SQLVal
	,ROUND(ABS(CONVERT(float, AccessVal,1)),0) as AccessFloat
	,ROUND(ABS(CONVERT(float, SQLVal,1)),0) as SQLFloat
FROM QA
WHERE QA_AutoID in (
	SELECT TOP 1 QA_AutoID 
	FROM @MyQA
	)
AND ROUND(ABS(CONVERT(float, AccessVal,1)),0) <> ROUND(ABS(CONVERT(float, SQLVal,1)),0)
ORDER BY ROUND(ABS(CONVERT(float, AccessVal,1)),0) DESC
	,ROUND(ABS(CONVERT(float, SQLVal,1)),0) DESC

If I were you, I would probably choose the second method.

Tom

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!

Essential SQL Server Administration Tips - Online Course with Live Demonstrations and Hands-on Guides

(Lifetime Access/ Live Demos / Downloadable Resources and more!)

Enroll from $14.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!

Essential SQL Server Development Tips for SQL Developers - Online Course

(Lifetime Access, Certificate of Completion, downloadable resources and more!)

Enroll from $14.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:

  • The Database Engine system data directory in the registry is not valid
  • 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.

Snippets Generator - SQL Snippets Creation Tool

Learn more

Dynamic SQL Generator: Convert static T-SQL code to dynamic and vice versa, easily and fast.

Dynamic SQL Generator: Easily convert static SQL Server T-SQL scripts to dynamic and vice versa.

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).

The Philosophy and Fundamentals of Computer Programming - Online Course - Get Started with C, C++, C#, Java, SQL and Python

(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 $14.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: 1 Star2 Stars3 Stars4 Stars5 Stars (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

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: 25,940

Содержание

  1. Issue with join: Error converting data type nvarchar to float?
  2. 2 Answers 2
  3. Error converting data type nvarchar to float ms sql
  4. Answered by:
  5. Question
  6. Answers
  7. SQL Server: error converting data type nvarchar to float
  8. 3 Answers 3
  9. Hint 1: Float is the wrong type for this!
  10. Hint 2: NVarchar is the wrong type for this!
  11. UPDATE
  12. UPDATE 2
  13. Error unable to convert data type nvarchar to float
  14. 2 Answers 2
  15. Error converting data type nvarchar to float ms sql
  16. Answered by:
  17. Question
  18. Answers

Issue with join: Error converting data type nvarchar to float?

I’ve been trying to run the program below and I keep on getting the error

Error converting data type nvarchar to float

When 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.

2 Answers 2

The error message clearly says that the issue has to do with conversion of an nvarchar to a float . There’s no explicit conversion in your query, therefore it’s about implicit one. If the issue indeed stems from this particular query and not from somewhere else, only two places can be responsible for that:

1) the join predicate;

2) the COALESCE call.

Both places involve one and the same pair of columns, a.File_NBR and b.File_NBR . So, one of them must be an nvarchar column and the other a float one. Since the float type has higher precedence than nvarchar , the latter would implicitly be converted to the former, not the other way around. And apparently one of the string values failed to convert. That’s the explanation of the immediate issue (the conversion).

I’ve seen your comment where you are saying that one of the columns is an int and the other float . I have no problem with that as I believe you are talking about columns in physical tables whereas both sources in this query appear to be views, judging by their names. I believe one of the columns enjoys a transformation to nvarchar in a view, and this query ends up seeing it as such. So, that should account for you where the nvarchar can come from.

As for an explanation to why commenting a seemingly irrelevant condition out appears to make such a big difference, the answer must lie in the internals of the query planner’s workings. While there’s a documented order of logical evaluation of clauses in a Transact-SQL SELECT query, the real, physical order may differ from that. The actual plan chosen for the query determines that physical order. And the choice of a plan can be affected, in particular, by such a trivial thing as incorporation or elimination of a simple condition.

To apply that to your situation, when the offending condition is commented out, the planner chooses such a plan for the query that both the join predicate and the COALESCE expression evaluate only when all the rows capable of causing the issue in question have been filtered out by predicates in the underlying views. When the condition is put back, however, the query is assigned a different execution plan, and either COALESCE or (more likely) the join predicate ends up being applied to a row containing a string that cannot be converted to a float, which results in an exception raised.

Conversion of both a.File_NBR and b.File_NBR to char , as you did, is one way of solving the issue. You could in fact pick any of these four string types:

And since one of the columns is already a string (possibly the a.File_NBR one, but you are at a better position to find that out exactly), the conversion could be applied to the other one only.

Alternatively, you could look into the view producing the nvarchar column to try and see if the int to nvarchar conversion could be eliminated in the first place.

Источник

Error converting data type nvarchar to float ms sql

This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

Answered by:

Question

This one has me stumped.

In the following code I want to compare 2 values: AccessVal and SQLVal. The values are stored as nvarchars, so I’m isolating the numeric values in a subquery. Notice I’m only selecting 1 row. The commented line, where I compare the values, is throwing the error.

Here is the output with the comparison commented out.

Here’s what I get with the comparison line activated:

I’ve tried converting to numeric, int and bigint instead of float. I’ve tried CAST instead of CONVERT. Nothing works.

Darrell H Burns

Answers

There are two things that need to be fixed.

First, you need a test that can be used in SQL 2008R2 to determine if a number can be converted to a float. A test that should work for you is to combine IsNumeric() with a regular expression that ensures that the string contains only characters that are valid to be converted to a float. So the following will test if the columns SQLVal and AccessVal can be converted to floats without error.

But your second problem is that SQL can process the query in any order it chooses. So even if your WHERE clause only chooses rows that can be converted to float, SQL might convert ALL of the rows to float and only later check the WHERE clause and throw away the rows that don’t match the WHERE clause. Of course, in your case, if SQL does this, you geet a conversion error before the WHERE clause is processed and the statement fails.

There are two ways you can fix this, one of which leaves this as a single query, but will make your query longer and more complex, the other will split your query into two queries. That way might make your query less efficient depending on what your are doing (although, in this case, I don’t think that will be a problem).

In the first way, you would change the WHERE clause of the query as above, and the everywhere where you do a convert you would add a CASE statement that makes sure you do not attempt to convert an invalid value. So, for example, in your SELECT clause, instead of

To be totally safe, you would need to make this change to add the CASE everywhere in your query where you have a CONVERT to float.

The second way would be to Create a temp table or table variable with one column named QA_AutoID. Then insert into that table only rows which have valid floats in the columns. Then use that temp table or variable in your query. Since that is now two SQL statements, the WHERE selecting only valid floats in the first query will always be done before any converts in the second query. That would look something like

If I were you, I would probably choose the second method.

Источник

SQL Server: error converting data type nvarchar to float

I have read many articles and tried several methods but don’t have any luck.

I am importing table A (whose cost is char to table B (which requires float ).

And I still get this error:

Error converting data type nvarchar to float

In addition, I am not sure how to modify the existing code based on the answers;

The existing code structure

I also tried CAST(test AS FLOAT) AS CastedValue

Why float ? The dataset will be sent to an optimization algorithm which requires float . Thanks for pointing it out though.

3 Answers 3

This works for me?

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

I do not know the target table’s column names, but this should work

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.

Источник

Error unable to convert data type nvarchar to float

I have searched both this great forum and googled around but unable to resolve this.

We have two tables (and trust me I have nothing to do with these tables). Both tables have a column called eventId .

However, in one table, data type for eventId is float and in the other table, it is nvarchar .

We are selecting from table1 where eventI is defined as float and saving that Id into table2 where eventId is defined as nvarchar(50) .

As a result of descrepancy in data types, we are getting error converting datatype nvarchar to float .

Without fooling around with the database, I would like to cast the eventId to get rid of this error.

Any ideas what I am doing wrong with the code below?

2 Answers 2

The problem is most likely because some of the rows have event_id that is empty. There are two ways to go about solving this:

  • Convert your float to nvarchar , rather than the other way around — This conversion will always succeed. The only problem here is if the textual representations differ — say, the table with float -as- nvarchar uses fewer decimal digits, or
  • Add a condition to check for empty IDs before the conversion — This may not work if some of the event IDs are non-empty strings, but they are not float-convertible either (e.g. there’s a word in the field instead of a number).

The second solution would look like this:

Convert float to nvarchar instead of nvarchar to float. Of course!

Источник

Error converting data type nvarchar to float ms sql

This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

Answered by:

Question

This one has me stumped.

In the following code I want to compare 2 values: AccessVal and SQLVal. The values are stored as nvarchars, so I’m isolating the numeric values in a subquery. Notice I’m only selecting 1 row. The commented line, where I compare the values, is throwing the error.

Here is the output with the comparison commented out.

Here’s what I get with the comparison line activated:

I’ve tried converting to numeric, int and bigint instead of float. I’ve tried CAST instead of CONVERT. Nothing works.

Darrell H Burns

Answers

There are two things that need to be fixed.

First, you need a test that can be used in SQL 2008R2 to determine if a number can be converted to a float. A test that should work for you is to combine IsNumeric() with a regular expression that ensures that the string contains only characters that are valid to be converted to a float. So the following will test if the columns SQLVal and AccessVal can be converted to floats without error.

But your second problem is that SQL can process the query in any order it chooses. So even if your WHERE clause only chooses rows that can be converted to float, SQL might convert ALL of the rows to float and only later check the WHERE clause and throw away the rows that don’t match the WHERE clause. Of course, in your case, if SQL does this, you geet a conversion error before the WHERE clause is processed and the statement fails.

There are two ways you can fix this, one of which leaves this as a single query, but will make your query longer and more complex, the other will split your query into two queries. That way might make your query less efficient depending on what your are doing (although, in this case, I don’t think that will be a problem).

In the first way, you would change the WHERE clause of the query as above, and the everywhere where you do a convert you would add a CASE statement that makes sure you do not attempt to convert an invalid value. So, for example, in your SELECT clause, instead of

To be totally safe, you would need to make this change to add the CASE everywhere in your query where you have a CONVERT to float.

The second way would be to Create a temp table or table variable with one column named QA_AutoID. Then insert into that table only rows which have valid floats in the columns. Then use that temp table or variable in your query. Since that is now two SQL statements, the WHERE selecting only valid floats in the first query will always be done before any converts in the second query. That would look something like

If I were you, I would probably choose the second method.

Источник

Понравилась статья? Поделить с друзьями:
  • Ms sql error 207
  • Ms sql error 20476
  • Ms sql error 15105
  • Ms sql database restoring state как исправить
  • Ms sql arithmetic overflow error converting float to data type numeric