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
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
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!
(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!
(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.
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 $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: (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: 25,985
-
December 15, 2016 at 6:03 am
#319754
Hi
Error converting data type nvarchar to float is returning
Select Convert(mycolumn as float) from mytable;
mycolumn is nvarchar(100)
but my destination table is float , so i am converting to float, but getting error «Error converting data type nvarchar to float«
there are 10 million records in it, dont know which record is causing problem. how to sought it .
Advance thanks!
-
Anand BI Developer
SSCommitted
Points: 1772
Hi ,
normally its working .
better you post some sample data or check any chacters or (comma , instead of dot . found) ..! then only we can able to fix your real-time bugs.
use tempdb
create table test1(number nvarchar(100))
insert into test1 values(‘120450,454852’),(‘120450.454852’),(‘14520450.454852’),(‘100000.45454852’)
— select number , cast(number as float) + 1.0 as conversion from test1 — > Error
select number , cast(replace(number,’,’,’.’) as float) + 1.0 as conversion from test1 — > Solution
-
ChrisM@Work
SSC Guru
Points: 186127
yuvipoy (12/15/2016)
Hi
Error converting data type nvarchar to float is returning
Select Convert(mycolumn as float) from mytable;
mycolumn is nvarchar(100)
but my destination table is float , so i am converting to float, but getting error «Error converting data type nvarchar to float«
there are 10 million records in it, dont know which record is causing problem. how to sought it .
Advance thanks!
SELECT mycolumn, x.mycolumnAsFloat
FROM mytable
CROSS APPLY (SELECT mycolumnAsFloat = TRY_CONVERT(float,mycolumn) ) x
WHERE x.mycolumnAsFloat IS NULL
-
sgmunson
SSC Guru
Points: 110620
yuvipoy (12/15/2016)
Hi
Error converting data type nvarchar to float is returning
Select Convert(mycolumn as float) from mytable;
mycolumn is nvarchar(100)
but my destination table is float , so i am converting to float, but getting error «Error converting data type nvarchar to float«
there are 10 million records in it, dont know which record is causing problem. how to sought it .
Advance thanks!
You can at least try to find the errors this way:
SELECT *
FROM mytable
WHERE ISNUMERIC(mycolumn) = 0
This may not catch everything, but as you’re looking to convert to float, it might well catch the vast majority. If you were on a higher version of SQL Server, such as SQL 2012, you could use TRY_CONVERT(float, mycolumn), which would return NULL values where mycolumn could not be converted. You’d also have to only check non-null values of mycolumn, but I think you get the idea.
-
sgmunson
SSC Guru
Points: 110620
ChrisM@Work (12/15/2016)
yuvipoy (12/15/2016)
Hi
Error converting data type nvarchar to float is returning
Select Convert(mycolumn as float) from mytable;
mycolumn is nvarchar(100)
but my destination table is float , so i am converting to float, but getting error «Error converting data type nvarchar to float«
there are 10 million records in it, dont know which record is causing problem. how to sought it .
Advance thanks!
SELECT mycolumn, x.mycolumnAsFloat
FROM mytable
CROSS APPLY (SELECT mycolumnAsFloat = TRY_CONVERT(float,mycolumn) ) x
WHERE x.mycolumnAsFloat IS NULL
Chris,
That’s a SQL 2012 feature, and this is a 2008 forum…
-
ChrisM@Work
SSC Guru
Points: 186127
sgmunson (12/15/2016)
ChrisM@Work (12/15/2016)
yuvipoy (12/15/2016)
Hi
Error converting data type nvarchar to float is returning
Select Convert(mycolumn as float) from mytable;
mycolumn is nvarchar(100)
but my destination table is float , so i am converting to float, but getting error «Error converting data type nvarchar to float«
there are 10 million records in it, dont know which record is causing problem. how to sought it .
Advance thanks!
SELECT mycolumn, x.mycolumnAsFloat
FROM mytable
CROSS APPLY (SELECT mycolumnAsFloat = TRY_CONVERT(float,mycolumn) ) x
WHERE x.mycolumnAsFloat IS NULL
Chris,
That’s a SQL 2012 feature, and this is a 2008 forum…
Oh cr@p, thanks Steve.
-
yuvipoy
SSChampion
Points: 10469
Anandkumar-SQL_Developer (12/15/2016)
Hi ,
normally its working .
better you post some sample data or check any chacters or (comma , instead of dot . found) ..! then only we can able to fix your real-time bugs.
Thanks Anandkumar..!! this are some preliminary checks which done before posting…
Thanks all.
Select Convert(float as mycolumn) from table —>gives error
Select TRY_CONVERT(FLOAT, mycolumn) from table —> did not give error when tried in SQL server 2012.
Wondering what is the difference and why SQL server 2008 convert(float ) did not worked 🙁 , these many days it was working ?
SELECT *
FROM mytable
WHERE ISNUMERIC(mycolumn) = 0
does not return anything — Zero rows
-
twin.devil
SSC-Insane
Points: 22208
Both CONVERT and TRY_CONVERT function converts the expression to the requested type. But if the CONVERT function fails to convert the value to the requested type then raises an exception, on the other hand if TRY_CONVERT function returns a NULL value if it fails to convert the value to the requested type.
Below example demonstrates this difference:
SELECT CONVERT(float, '.') AS 'CONVERT Function Result'
SELECT TRY_CONVERT(float, '.') AS 'TRY_CONVERT Function Result'
Furthermore, ISNUMERIC() is not a very good function to determine whether data is a proper numeric or not
Below example demonstrates this:
Select ISNUMERIC('.') AS 'IsNumeric Function Result' --- Will be considered as numeric
Select CONVERT(float, '.') AS 'CONVERT Function Result' --- Will raise an error
First you need to identify what is causing values are causing this for this you can use ChrisM@Work query. Once you identify those data anomalies it will be easy for you to rectify them.
Hope it helps
-
yuvipoy
SSChampion
Points: 10469
No actually i guess there is an issue in SQL server 2012 which ever data column which is having as float or convert(float ) has an issue,where as in SQL server 2016 there is no issue.
Since my origin database is SQL server 2008R2 i posted here..
Which ever data is there in SQL server 2008R2 having float column when ran on SQL server 2012 there is an issue, where as same in SQL server 2016 there is no issue. tested more than 5 times 🙂 🙂
-
sgmunson
SSC Guru
Points: 110620
yuvipoy (12/16/2016)
No actually i guess there is an issue in SQL server 2012 which ever data column which is having as float or convert(float ) has an issue,where as in SQL server 2016 there is no issue.
Since my origin database is SQL server 2008R2 i posted here..
Which ever data is there in SQL server 2008R2 having float column when ran on SQL server 2012 there is an issue, where as same in SQL server 2016 there is no issue. tested more than 5 times 🙂 🙂
Are you sure you aren’t just getting NULL values from conversions that fail but don’t create an exception? Also, can you detect the difference between a NULL generated because the field to be converted has a NULL value and a NULL generated because of a failed conversion?
-
December 20, 2016 at 9:21 pm
This was removed by the editor as SPAM
Viewing 11 posts — 1 through 10 (of 10 total)
Я хочу преобразовать данные nvarchar
в тип float
.
В моем случае у меня есть столбец SalesValue
, и я использовал эту команду
UPDATE Overseas
SET SalesValue = CONVERT(FLOAT, REPLACE([SalesValue],',','') )
Моя таблица имеет такие значения, как
201.01
40.50
215.12
550
304.201
Но я получаю ошибку
SQL: Ошибка при преобразовании типа данных nvarchar в float.
Как я могу решить эту проблему ?
4 ответа
Лучший ответ
1-е приведение значения с помощью запроса ниже, а затем обновите нормально
SELECT
case when ISNUMERIC([SalesValue])=1
then CAST([SalesValue] AS FLOAT) else 0 end AS CastedValue)
FROM your_table_name
0
Zaynul Abadin Tuhin
6 Июн 2017 в 12:41
Это приблизит вас к ISNUMERIC()
declare @table table (SalesValue varchar(16))
insert into @table
values
('1e4'),
('$'),
('134.55'),
('66,9897'),
('14')
select
SalesValue
,case
when SalesValue NOT LIKE '%[^0-9,.]%'
then convert(decimal(16,4),replace(SalesValue,',','.'))
end
from
@table
0
scsimon
6 Июн 2017 в 13:35
Вы должны найти значения, которые не совпадают. В SQL Server 2012+ вы можете использовать try_convert()
. Это не доступно. Так как насчет этого?
SELECT SalesValue
FROM Overseas
WHERE SalesValue LIKE '%[^0-9,.]%' OR
SalesValue LIKE '%[.,]%[.,]%';
Я думаю, что это покрывает очевидные нарушения: символ, который не является числовым или двумя (или более) десятичными точками.
1
Gordon Linoff
5 Июн 2017 в 20:57
Похоже, что у вас все еще есть не числовые данные. Я надеюсь, что ваша сторона приложения проделала довольно хорошую работу по очистке ваших данных перед вводом, и проблема, вероятно, в том, что у вас есть «$» в одном или нескольких ваших полях. Преобразование завершится неудачно, когда у вас будет не числовой символ, отличный от ‘.’ в нем (как вы, вероятно, знаете, именно поэтому вы удалили ‘,’). Я запустил приведенный ниже скрипт, чтобы проверить это.
declare @myFloat float;
declare @test1 nvarchar(10) = '145.88';
declare @test2 nvarchar(10) = '4,145.88';
declare @test3 nvarchar(10) = '$4,145.88';
SELECT ISNUMERIC(@TEST3)
set @myFloat = CONVERT(FLOAT, REPLACE(@test1,',','') );
select @myFloat;
set @myFloat = CONVERT(FLOAT, REPLACE(@test2,',','') );
select @myFloat;
--THIS WILL FAIL
set @myFloat = CONVERT(FLOAT, REPLACE(@test3,',','') );
select @myFloat;
--THIS WILL NOT FAIL
set @myFloat = CONVERT(FLOAT, REPLACE(REPLACE(@test3,',',''),'$','') );
select @myFloat;
Вы можете попробовать запустить приведенный ниже скрипт для рассматриваемого столбца, чтобы увидеть, с какими столбцами у вас возникла проблема:
--run this on your table
SELECT SalesValue
FROM Overseas
WHERE ISNUMERIC(REPLACE(SalesValue,',','')) = 0
--test sample
/*
insert into #myTable
values ('145.88'),
('4,145.88'),
('$4,145.88'),
('$4,145.88%');
SELECT *
FROM #myTable
WHERE ISNUMERIC(REPLACE(amounts,',','')) = 0
--WHERE ISNUMERIC(REPLACE(REPLACE(amounts,',',''),'$','')) = 0 --this will remove results with $ also
*/
Таким образом, ваше исправление будет состоять в том, чтобы просто изменить предоставленную вами строку:
UPDATE Overseas SET SalesValue = CONVERT(FLOAT, REPLACE(REPLACE([SalesValue],',',''),'$','') )
Если вы не нашли другие символы в результатах предыдущего сценария.
0
chris
5 Июн 2017 в 22:16