Ошибка при преобразовании типа данных varchar к float sql

CASE
WHEN (Cast(CONVERT(DECIMAL(10,2),(totaleffort/7.40)) as nvarchar)- FLOOR(Cast(CONVERT(DECIMAL(10,2),(totaleffort/7.40)) as nvarchar)))> 0 AND (Cast(CONVERT(DECIMAL(10,2),(totaleffort/7.40)) as nvarchar)- FLOOR(Cast(CONVERT(DECIMAL(10,2),(totaleffort/7.40)) as nvarchar)))<=0.25 THEN (0.25+FLOOR(Cast(CONVERT(DECIMAL(10,2),(totaleffort/7.40)) as nvarchar)))

WHEN (Cast(CONVERT(DECIMAL(10,2),(totaleffort/7.40)) as nvarchar)- FLOOR(Cast(CONVERT(DECIMAL(10,2),(totaleffort/7.40)) as nvarchar)))> 0.25 AND (Cast(CONVERT(DECIMAL(10,2),(totaleffort/7.40)) as nvarchar)- FLOOR(Cast(CONVERT(DECIMAL(10,2),(totaleffort/7.40)) as nvarchar)))<=0.50 THEN (0.50+FLOOR(Cast(CONVERT(DECIMAL(10,2),(totaleffort/7.40)) as nvarchar)))

WHEN (Cast(CONVERT(DECIMAL(10,2),(totaleffort/7.40)) as nvarchar)- FLOOR(Cast(CONVERT(DECIMAL(10,2),(totaleffort/7.40)) as nvarchar)))> 0.50 AND (Cast(CONVERT(DECIMAL(10,2),(totaleffort/7.40)) as nvarchar)- FLOOR(Cast(CONVERT(DECIMAL(10,2),(totaleffort/7.40)) as nvarchar)))<=0.75 THEN (0.75+FLOOR(Cast(CONVERT(DECIMAL(10,2),(totaleffort/7.40)) as nvarchar)))

WHEN (Cast(CONVERT(DECIMAL(10,2),(totaleffort/7.40)) as nvarchar)- FLOOR(Cast(CONVERT(DECIMAL(10,2),(totaleffort/7.40)) as nvarchar)))> 0.75 AND (Cast(CONVERT(DECIMAL(10,2),(totaleffort/7.40)) as nvarchar)- FLOOR(Cast(CONVERT(DECIMAL(10,2),(totaleffort/7.40)) as nvarchar)))<1 THEN (1+FLOOR(Cast(CONVERT(DECIMAL(10,2),(totaleffort/7.40)) as nvarchar)))


WHEN (Cast(CONVERT(DECIMAL(10,2),(totaleffort/7.40)) as nvarchar)- FLOOR(Cast(CONVERT(DECIMAL(10,2),(totaleffort/7.40)) as nvarchar)))= 0 THEN (0+FLOOR(Cast(CONVERT(DECIMAL(10,2),(totaleffort/7.40)) as nvarchar)))

END

AS Estimated_Effort_Days,

The above code is currently rounding up a field called totaleffort to the nearest.25, for example if i have a value of 78.19 it will round up to 78.25.

I have a new requirement for the value of zero, when the value = 0 then i need to display the text ‘unknown number’ I have attempted to add an additional case statement however the query fails to run with an error :

Error converting data type varchar to float.

Does anyone have a reccomendation for me

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 $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!

Essential SQL Server Development Tips for SQL Developers - Online Course

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

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 $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: 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: 29,031

I have the following SQL statement which is giving me this error.

«Error converting data type varchar to float» in this line

   ,  pe.ProductWeight + ' lb' AS weight

I realize this is wrong but I don’t know how to add «lb» to the weight value. Any help would be appreciated.

SELECT p.ProductCode AS id

,  p.ProductName AS title

,  'Home & Garden > Household Appliance Accessories > Laundry Appliance Accessories' AS product_type

,  IsNull(pe.SalePrice,pe.ProductPrice) AS price

,  IsNull(pe.ProductManufacturer,'n/a') AS brand

,  IsNull(pe.ProductCondition,'new') AS condition

,  CONVERT(VARCHAR(10), (GETDATE() + 30),120) AS expiration_date

,  pd.ProductDescriptionShort AS [stripHTML-description]

,  'http://www.thesite.com/v/vspfiles/photos/' + IsNull(p.Vendor_PartNo,p.ProductCode) + '-2.jpg' AS image_link

,  'http://www.thesite.asp?ProductCode=' + p.ProductCode + '&Click=1327'  AS link

,  pe.ProductWeight + ' lb' AS weight


FROM Products p

INNER JOIN Products_Descriptions pd ON p.ProductID = pd.ProductID

INNER JOIN Products_Extended pe ON pd.ProductID = pe.ProductID

WHERE (p.IsChildOfProductCode is NULL OR p.IsChildOfProductCode = ' AND (p.HideProduct is NULL OR p.HideProduct <> 'Y')

AND (pe.ProductPrice > 0)

ORDER BY p.ProductCode

  • Remove From My Forums
  • Question

  • I have this query:

    SELECT
    A.[ID EMPLEADO],A.EMPLEADO,
    LTRIM(A.EMPRESA) AS EMPRESA,
    CASE A.EMPRESA
        WHEN ‘OHSC’ THEN ‘OHSC’
        ELSE ‘OH’
    END AS OH,
    A.[CLAVE PUESTO PS],A.[PUESTO PS],
    CONVERT(DECIMAL,A.[CLAVE CLIENTE]) AS [CLAVE CLIENTE],AN.CLIENTE,A.[CLAVE CC],A.CC,
    A.FECHA_INGRESO,MONTH(A.FECHA_INGRESO) AS MES,YEAR(A.FECHA_INGRESO) AS AÑO,
    AN.SUCURSAL,AN.[GERENCIA REGIONAL],
    ISNULL(AN.CORPORATIVO,A.CLIENTE) AS CORPORATIVO,
    AN.[PARQUE INDUSTRIAL],AN.GIRO,
    GENERO,dbo.fn_RangoEdad(FECHA_NACIMIENTO) AS [RANGO EDAD]
    FROM ALTAS A
    LEFT JOIN AgrupadoresNomina AN ON A.[CLAVE CLIENTE]=AN.[CLAVE CLIENTE]
    EXCEPT
    SELECT * FROM vBajas_Cancelacion_PS

    That query was working fine, but recently has started to give me the following message:

    Msg 8114, Level 16, State 5, Line 1
    Error converting data type varchar to float.

    I’ve tried running the first SELECT, and everything is OK, running the second SELECT and everything is OK.

    Also i’ve tried changing the EXCEPT sentence for NOT IN or EXIST (in this case it only shows me 34086 records, then gives me same error), removing the CONVERT from the query, but the result is the same, it gives me the «Error converting data type varchar
    to float» message.

    Can someone help me to get more ideas to find the record or why is now showing me this message?

    Thanks in advance!

Answers

  • You are seeing that message because in one of those selects there is a float column and the corresponding column in the other select is a varchar.  So when yoou run one select, you get a float result so there is no problem.  When you run the other
    select, you get a varchar result, so that is also no problem.  But when you run them together with the EXCEPT, SQL must convert them to the same type in order to do the compare.  Since float has a higher priority than varchar, SQL tries to convert
    the value in the varchar column to a float.  So for at least one row, you have a value in that varchar column which cannot be converted.

    If you are on SQL 2012 or later, the best way to find the row(s) causing this error is to run (in the code below, replace <column name> with the name of the varchar column.

    Select <column name>
    From ...
    Where Try_Convert(float, <column name>) Is Null And <column name> Is Not Null;

    If you are on SQL 2008R2 or earlier, you cannot use Try_Convert, but you can do

    Select <column name>
    From ...
    Where IsNumeric(<column name>) = 0;

    That’s not quite as helpful as Try_Convert.  If will probably find the row(s) but it might not depending exactly what is in the varchar column.

    In addition to selecting the column name, you might also want to select any additional data needed to find the row with the bad data (such as the primary key columns).

    Tom

    • Marked as answer by

      Wednesday, February 20, 2013 3:48 AM

  • Does the column datatypes from both SELECT statements are compatible ?

    As a test, try inserting the first SELECT statement results into a temp table and then check the data types of all those columns whether compatible with t all column data types of the table/view —

    vBajas_Cancelacion_PS (second SELECT statement)

    SELECT
    A.[ID EMPLEADO],A.EMPLEADO,
    LTRIM(A.EMPRESA) AS EMPRESA,
    CASE A.EMPRESA
        WHEN 'OHSC' THEN 'OHSC'
        ELSE 'OH'
    END AS OH,
    A.[CLAVE PUESTO PS],A.[PUESTO PS],
    CONVERT(DECIMAL,A.[CLAVE CLIENTE]) AS [CLAVE CLIENTE],AN.CLIENTE,A.[CLAVE CC],A.CC,
    A.FECHA_INGRESO,MONTH(A.FECHA_INGRESO) AS MES,YEAR(A.FECHA_INGRESO) AS AÑO,
    AN.SUCURSAL,AN.[GERENCIA REGIONAL],
    ISNULL(AN.CORPORATIVO,A.CLIENTE) AS CORPORATIVO,
    AN.[PARQUE INDUSTRIAL],AN.GIRO,
    GENERO,dbo.fn_RangoEdad(FECHA_NACIMIENTO) AS [RANGO EDAD]
    INTO FirstSelectResults -- Added this
    FROM ALTAS A
    LEFT JOIN AgrupadoresNomina AN ON A.[CLAVE CLIENTE]=AN.[CLAVE CLIENTE]

    SP_HELP FirstSelectResults 


    Narsimha

    • Marked as answer by
      AlejandroVR
      Wednesday, February 20, 2013 3:49 AM

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 $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!

Essential SQL Server Development Tips for SQL Developers - Online Course

(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:

  • 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 $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: 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,686

  • Remove From My Forums
  • Question

  • I have this query:

    SELECT
    A.[ID EMPLEADO],A.EMPLEADO,
    LTRIM(A.EMPRESA) AS EMPRESA,
    CASE A.EMPRESA
        WHEN ‘OHSC’ THEN ‘OHSC’
        ELSE ‘OH’
    END AS OH,
    A.[CLAVE PUESTO PS],A.[PUESTO PS],
    CONVERT(DECIMAL,A.[CLAVE CLIENTE]) AS [CLAVE CLIENTE],AN.CLIENTE,A.[CLAVE CC],A.CC,
    A.FECHA_INGRESO,MONTH(A.FECHA_INGRESO) AS MES,YEAR(A.FECHA_INGRESO) AS AÑO,
    AN.SUCURSAL,AN.[GERENCIA REGIONAL],
    ISNULL(AN.CORPORATIVO,A.CLIENTE) AS CORPORATIVO,
    AN.[PARQUE INDUSTRIAL],AN.GIRO,
    GENERO,dbo.fn_RangoEdad(FECHA_NACIMIENTO) AS [RANGO EDAD]
    FROM ALTAS A
    LEFT JOIN AgrupadoresNomina AN ON A.[CLAVE CLIENTE]=AN.[CLAVE CLIENTE]
    EXCEPT
    SELECT * FROM vBajas_Cancelacion_PS

    That query was working fine, but recently has started to give me the following message:

    Msg 8114, Level 16, State 5, Line 1
    Error converting data type varchar to float.

    I’ve tried running the first SELECT, and everything is OK, running the second SELECT and everything is OK.

    Also i’ve tried changing the EXCEPT sentence for NOT IN or EXIST (in this case it only shows me 34086 records, then gives me same error), removing the CONVERT from the query, but the result is the same, it gives me the «Error converting data type varchar
    to float» message.

    Can someone help me to get more ideas to find the record or why is now showing me this message?

    Thanks in advance!

Answers

  • You are seeing that message because in one of those selects there is a float column and the corresponding column in the other select is a varchar.  So when yoou run one select, you get a float result so there is no problem.  When you run the other
    select, you get a varchar result, so that is also no problem.  But when you run them together with the EXCEPT, SQL must convert them to the same type in order to do the compare.  Since float has a higher priority than varchar, SQL tries to convert
    the value in the varchar column to a float.  So for at least one row, you have a value in that varchar column which cannot be converted.

    If you are on SQL 2012 or later, the best way to find the row(s) causing this error is to run (in the code below, replace <column name> with the name of the varchar column.

    Select <column name>
    From ...
    Where Try_Convert(float, <column name>) Is Null And <column name> Is Not Null;

    If you are on SQL 2008R2 or earlier, you cannot use Try_Convert, but you can do

    Select <column name>
    From ...
    Where IsNumeric(<column name>) = 0;

    That’s not quite as helpful as Try_Convert.  If will probably find the row(s) but it might not depending exactly what is in the varchar column.

    In addition to selecting the column name, you might also want to select any additional data needed to find the row with the bad data (such as the primary key columns).

    Tom

    • Marked as answer by

      Wednesday, February 20, 2013 3:48 AM

  • Does the column datatypes from both SELECT statements are compatible ?

    As a test, try inserting the first SELECT statement results into a temp table and then check the data types of all those columns whether compatible with t all column data types of the table/view —

    vBajas_Cancelacion_PS (second SELECT statement)

    SELECT
    A.[ID EMPLEADO],A.EMPLEADO,
    LTRIM(A.EMPRESA) AS EMPRESA,
    CASE A.EMPRESA
        WHEN 'OHSC' THEN 'OHSC'
        ELSE 'OH'
    END AS OH,
    A.[CLAVE PUESTO PS],A.[PUESTO PS],
    CONVERT(DECIMAL,A.[CLAVE CLIENTE]) AS [CLAVE CLIENTE],AN.CLIENTE,A.[CLAVE CC],A.CC,
    A.FECHA_INGRESO,MONTH(A.FECHA_INGRESO) AS MES,YEAR(A.FECHA_INGRESO) AS AÑO,
    AN.SUCURSAL,AN.[GERENCIA REGIONAL],
    ISNULL(AN.CORPORATIVO,A.CLIENTE) AS CORPORATIVO,
    AN.[PARQUE INDUSTRIAL],AN.GIRO,
    GENERO,dbo.fn_RangoEdad(FECHA_NACIMIENTO) AS [RANGO EDAD]
    INTO FirstSelectResults -- Added this
    FROM ALTAS A
    LEFT JOIN AgrupadoresNomina AN ON A.[CLAVE CLIENTE]=AN.[CLAVE CLIENTE]
    SP_HELP FirstSelectResults 

    Narsimha

    • Marked as answer by
      AlejandroVR
      Wednesday, February 20, 2013 3:49 AM

Вопрос:

Поиск и поиск по SO и не может понять это
Пробовал CASTING в каждом поле как FLOAT безрезультатно, конвертер не получил меня дальше
Как я могу получить предложение ниже case, чтобы вернуть значение, указанное в разделе THEN?

Ошибка:
Msg 8114, уровень 16, состояние 5, строка 1
Ошибка преобразования типа данных varchar в float.

моего SQL-запроса, который делает ошибку:

When cust_trendd_w_costsv.terms_code like '%[%]%' and (prod.dbo.BTYS2012.average_days_pay) - (substring(cust_trendd_w_costsv.terms_code,3,2)) <= 5 THEN prod.dbo.cust_trendd_w_costsv.terms_code

average_days_pay = float
terms_code = char

Ура!

Лучший ответ:

Попробуйте использовать ISNUMERIC для обработки строк, которые нельзя преобразовать:

When cust_trendd_w_costsv.terms_code like '%[%]%' 
and (prod.dbo.BTYS2012.average_days_pay) - 

(case when isnumeric(substring(cust_trendd_w_costsv.terms_code,3,2))=1 
         then cast(substring(cust_trendd_w_costsv.terms_code,3,2) as float)
         else 0
 end)
<= 5 THEN prod.dbo.cust_trendd_w_costsv.terms_code

Ответ №1

Проблема, с которой вы сталкиваетесь, заключается в том, что вы специально ищете строки, содержащие символ %, а затем преобразовывая их (неявно или явно) в float.

Но строки, содержащие знаки %, не могут быть преобразованы в float, в то время как у них все еще есть %. Это также приводит к ошибке:

select CONVERT(float,'12.5%')

Если вы хотите конвертировать в float, сначала нужно удалить знак %, например:

CONVERT(float,REPLACE(terms_code,'%',''))

просто устранит его. Я не уверен, есть ли другие символы в столбце terms_code, которые могут также отключить его.

Вам также необходимо знать, что SQL Server может довольно агрессивно переупорядочить операции и поэтому может попытаться выполнить вышеуказанное преобразование в других строках в terms_code, даже те, которые не содержат %. Если это источник вашей ошибки, вам необходимо предотвратить этот агрессивный переупорядочивание. Если нет агрегатов, выражение CASE обычно может избежать наихудших проблем – убедитесь, что все строки, которые вы не хотите обрабатывать, устраняются более ранними предложениями WHEN, прежде чем пытаться преобразовать

Ответ №2

Если вы уверены, что Substring Part возвращает числовое значение, вы можете вставить подстроку (….) в Float:

 .....and (prod.dbo.BTYS2012.average_days_pay) - (CAST(substring(cust_trendd_w_costsv.terms_code,3,2)) as float ) <= 5 ....

The STR() function accepts a float datatype as the first argument, therefore SQL Server is implicitly converting whatever you pass to this function, which in your case is the CHAR(20) column. Since unknown can’t be converted to a float, you get the error.
If you run the following with the actual execution plan enabled:

DECLARE @T TABLE (Col CHAR(20));
INSERT @T VALUES (NULL);

SELECT Result = ISNULL(STR(Col, 25, 0), 'Missing')
FROM @T

Then checkthe execution plan XML you will see the implicit conversion:

<ScalarOperator ScalarString="isnull(str(CONVERT_IMPLICIT(float(53),[Col],0),(25),(0)),'Missing')">

The simplest solution is probably to use a case expression and not bother with any conversion at all (only if you know you will only have the 5 values you listed:

DECLARE @T TABLE (Col CHAR(20));
INSERT @T VALUES (NULL), ('0'), ('50'), ('100');--, ('Unknown');

SELECT Result = CASE WHEN Col IS NULL OR Col = 'Unknown' THEN 'Missing' ELSE Col END
FROM @T;

Result
---------
Missing
0                   
50                  
100                 
Missing             

If you really want the STR() function, you can make the conversion explicit, but use TRY_CONVERT() so that anything that is not a float simply returns NULL:

DECLARE @T TABLE (Col CHAR(20));
INSERT @T VALUES (NULL), ('0'), ('50'), ('100');--, ('Unknown');

SELECT Result = ISNULL(STR(TRY_CONVERT(FLOAT, Col), 25, 0), 'Missing')
FROM @T

Result
------------
Missing
        0   
       50
      100
Missing

Although, since you the numbers you have stated are integers, I would be inclined to convert them to integers rather than floats:

DECLARE @T TABLE (Col CHAR(20));
INSERT @T VALUES (NULL), ('0'), ('50'), ('100'), ('Unknown');

SELECT Result = ISNULL(CONVERT(VARCHAR(10), TRY_CONVERT(INT, Col)), 'Missing')
FROM @T;

Result
---------
Missing
0                   
50                  
100                 
Missing      

The STR() function accepts a float datatype as the first argument, therefore SQL Server is implicitly converting whatever you pass to this function, which in your case is the CHAR(20) column. Since unknown can’t be converted to a float, you get the error.
If you run the following with the actual execution plan enabled:

DECLARE @T TABLE (Col CHAR(20));
INSERT @T VALUES (NULL);

SELECT Result = ISNULL(STR(Col, 25, 0), 'Missing')
FROM @T

Then checkthe execution plan XML you will see the implicit conversion:

<ScalarOperator ScalarString="isnull(str(CONVERT_IMPLICIT(float(53),[Col],0),(25),(0)),'Missing')">

The simplest solution is probably to use a case expression and not bother with any conversion at all (only if you know you will only have the 5 values you listed:

DECLARE @T TABLE (Col CHAR(20));
INSERT @T VALUES (NULL), ('0'), ('50'), ('100');--, ('Unknown');

SELECT Result = CASE WHEN Col IS NULL OR Col = 'Unknown' THEN 'Missing' ELSE Col END
FROM @T;

Result
---------
Missing
0                   
50                  
100                 
Missing             

If you really want the STR() function, you can make the conversion explicit, but use TRY_CONVERT() so that anything that is not a float simply returns NULL:

DECLARE @T TABLE (Col CHAR(20));
INSERT @T VALUES (NULL), ('0'), ('50'), ('100');--, ('Unknown');

SELECT Result = ISNULL(STR(TRY_CONVERT(FLOAT, Col), 25, 0), 'Missing')
FROM @T

Result
------------
Missing
        0   
       50
      100
Missing

Although, since you the numbers you have stated are integers, I would be inclined to convert them to integers rather than floats:

DECLARE @T TABLE (Col CHAR(20));
INSERT @T VALUES (NULL), ('0'), ('50'), ('100'), ('Unknown');

SELECT Result = ISNULL(CONVERT(VARCHAR(10), TRY_CONVERT(INT, Col)), 'Missing')
FROM @T;

Result
---------
Missing
0                   
50                  
100                 
Missing      
CASE
WHEN (Cast(CONVERT(DECIMAL(10,2),(totaleffort/7.40)) as nvarchar)- FLOOR(Cast(CONVERT(DECIMAL(10,2),(totaleffort/7.40)) as nvarchar)))> 0 AND (Cast(CONVERT(DECIMAL(10,2),(totaleffort/7.40)) as nvarchar)- FLOOR(Cast(CONVERT(DECIMAL(10,2),(totaleffort/7.40)) as nvarchar)))<=0.25 THEN (0.25+FLOOR(Cast(CONVERT(DECIMAL(10,2),(totaleffort/7.40)) as nvarchar)))

WHEN (Cast(CONVERT(DECIMAL(10,2),(totaleffort/7.40)) as nvarchar)- FLOOR(Cast(CONVERT(DECIMAL(10,2),(totaleffort/7.40)) as nvarchar)))> 0.25 AND (Cast(CONVERT(DECIMAL(10,2),(totaleffort/7.40)) as nvarchar)- FLOOR(Cast(CONVERT(DECIMAL(10,2),(totaleffort/7.40)) as nvarchar)))<=0.50 THEN (0.50+FLOOR(Cast(CONVERT(DECIMAL(10,2),(totaleffort/7.40)) as nvarchar)))

WHEN (Cast(CONVERT(DECIMAL(10,2),(totaleffort/7.40)) as nvarchar)- FLOOR(Cast(CONVERT(DECIMAL(10,2),(totaleffort/7.40)) as nvarchar)))> 0.50 AND (Cast(CONVERT(DECIMAL(10,2),(totaleffort/7.40)) as nvarchar)- FLOOR(Cast(CONVERT(DECIMAL(10,2),(totaleffort/7.40)) as nvarchar)))<=0.75 THEN (0.75+FLOOR(Cast(CONVERT(DECIMAL(10,2),(totaleffort/7.40)) as nvarchar)))

WHEN (Cast(CONVERT(DECIMAL(10,2),(totaleffort/7.40)) as nvarchar)- FLOOR(Cast(CONVERT(DECIMAL(10,2),(totaleffort/7.40)) as nvarchar)))> 0.75 AND (Cast(CONVERT(DECIMAL(10,2),(totaleffort/7.40)) as nvarchar)- FLOOR(Cast(CONVERT(DECIMAL(10,2),(totaleffort/7.40)) as nvarchar)))<1 THEN (1+FLOOR(Cast(CONVERT(DECIMAL(10,2),(totaleffort/7.40)) as nvarchar)))


WHEN (Cast(CONVERT(DECIMAL(10,2),(totaleffort/7.40)) as nvarchar)- FLOOR(Cast(CONVERT(DECIMAL(10,2),(totaleffort/7.40)) as nvarchar)))= 0 THEN (0+FLOOR(Cast(CONVERT(DECIMAL(10,2),(totaleffort/7.40)) as nvarchar)))

END

AS Estimated_Effort_Days,

Приведенный выше код в настоящее время округляет поле с именем totaleffort до ближайшего 25, например, если у меня значение 78.19, оно будет округлено до 78.25.

У меня есть новое требование для значения нуля, когда значение = 0, тогда мне нужно отобразить текст «неизвестный номер». Я попытался добавить дополнительный оператор case, однако запрос не выполняется с ошибкой:

Ошибка преобразования типа данных varchar в float.

Есть ли у кого-нибудь рекомендации для меня?

Friends,

Sometimes you need to convert the data of a column in SQL server table from VARCHAR(String) to FLOAT. When I was working on the similar one today i got an error saying that

Msg 8114, Level 16, State 5, Line 2
Error converting data type varchar to Float.

PFB the code I have written  –

SELECT col1, CAST(col2 AS FLOAT) as col2 FROM #DaTable

I was getting this error because there is some data like NULLS and non numeric values which cannot be converted to FLOAT datatype. To handle this kind of error we have to use the CASE Statement. PFB the converted code which converts VARCHAR column to FLOAT column.

SELECT col1,  
	CASE WHEN ISNUMERIC(col2) = 1
		THEN CAST(col2 AS FLOAT) 
		ELSE NULL 
	END as col2
FROM #tableName

In the above example at first point I am checking whether the data is NUMERIC or not using ISNUMERIC() function and if the data is non numeric then I am replacing the value with NULL as I cannot convert it to FLOAT type and then casting the data ONLY when it is NUMERIC to FLOAT.
Hope this helps !!
Regards,
Roopesh Babu V

  • Remove From My Forums
  • Вопрос

  • I work on SQL 2012 app Build dynamic query I get error 

    Error converting data type varchar to float.

    DECLARE @Header NVARCHAR(MAX)
    SELECT
        @Header = STUFF(
            (
    		
                SELECT ', ' +  case when A.splitFlag = 1 and a.value<> '-' and (a.Value is not null)   then ''''+A.DKFeatureName +''' as '''+A.DKFeatureName+''','''+ A.DKFeatureName + 'Units'  +''' as ''' + A.DKFeatureName +'Units' +'''' else ''''+A.DKFeatureName +''' as ''' + A.DKFeatureName +''''    end
                FROM #FinalTable A
    			where StatusId=2
            
                ORDER BY DisplayOrder
                FOR XML PATH ('')
            ),1,2,''
        )
        print @Header
    
    	
    
    
     DECLARE @Body NVARCHAR(MAX)
    SELECT
        @Body = STUFF(
            (
    		
    		SELECT ', ' +  case when A.splitFlag = 1  and a.value<> '-' and (a.Value is not null)  then 'LEFT(' + QUOTENAME (A.DKFeatureName) + ',PATINDEX(''%[^0-9.]%'',' + QUOTENAME (A.DKFeatureName) + ')-1) as ['+A.DKFeatureName+'],RIGHT('+ QUOTENAME (A.DKFeatureName) +',LEN('+ QUOTENAME (A.DKFeatureName) +') - PATINDEX(''%[^0-9.]%'','+ QUOTENAME (A.DKFeatureName) +')+1) as  ['+A.DKFeatureName +'Units'+']' else quotename(A.DKFeatureName) end
                FROM #FinalTable A 
    			where StatusId=2
    			     ORDER BY A.DisplayOrder
                FOR XML PATH ('')
            ),1,2,''
        )
        print @Body
    
    	
    	
    
     

    I have Error converting data type varchar to float

    I need to convert dynamic columns on @header and @Body

    so How to solve it

  • Ошибка при преобразовании типа данных varchar к bigint sql
  • Ошибка при преобразовании типа данных nvarchar к float sql
  • Ошибка при преобразовании типа данных nvarchar к datetime
  • Ошибка при преобразовании типа данных nvarchar к bigint
  • Ошибка при преобразовании типа данных float к decimal