Mssql error converting data type varchar to numeric

This article explains how you can resolve the data type conversion error message "error converting varchar to numeric" you might get in SQL Server.

While developing data processes in SQL Server, under certain circumstances, you might get the error message: error converting varchar to numeric. This error is similar with the conversion error you might get when you are trying to convert a varchar to float, etc.

Read on to find out the reason for getting this error message and how you can easily resolve it within just a minute.

The Numeric Data Type in SQL Server

Prior to discuss how you can reproduce and resolve the issue, it is important that you first understand the numeric data type in SQL Server. As described in the relevant MS Docs article, the numeric data type has fixed precision and scale, and it has equivalent functionality with the decimal data type.

Arguments

The numeric data type takes two arguments, that is precision and scale. The syntax is numeric(precision, scale).

Precision defines the maximum number of decimal digits (in both sides of the number) and its value range is between 1 and 38.

Scale, defines the number of decimal digit that will be stored to the right of the decimal point. Its value can range between 1 and the value specified for precision.

Here’s an example of a numeric data type value in SQL Server:

DECLARE @numValue NUMERIC(10,2);
SET @numValue=123456.7890

SELECT @numValue as NumValue;
GO

The number returned by the above T-SQL query is: 123456.7890

In the above example I specified as precision 10 and as scale 2.

So, even though I specified 123456.7890 as the numeric value, it was indirectly converted to a numeric(10,2) value and that’s why it returned the value 123456.79


Learn more tips like this! 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/ Live Demos / Downloadable Resources and more!)

Enroll from $14.99


Reproducing the Conversion Error

Great. Now, let’s reproduce the conversion error by trying to convert a “problematic” varchar value to numeric.

You can find this example below:

DECLARE @valueToConvert VARCHAR(50);
SET @valueToConvert='1123,456.7890';

SELECT CAST(@valueToConvert AS NUMERIC(10,2)) as ConvertedNumber;
GO

When you execute the above T-SQL code, you will get the below exact error message:

Msg 8114, Level 16, State 5, Line 4
Error converting data type varchar to numeric.

How to Resolve the Conversion Error

As you might have observed in the above example, the @valueToConvert variable, besides the dot (.), it also contains a comma (,).

Therefore, at the time of its conversion to the numeric data type, the comma is considered an illegal character for the destination data type (numeric) and that’s why you get the error message.

In order to resolve the conversion error, you just need to remove the comma (,) from the varchar value that you want to convert to numeric.

Note: At this point, you also need to make sure that the varchar value to be converted, is the actual number you wish to convert to the numeric data type. Also, you need to make sure that you only use the decimal symbol, in this case the dot (.), and not any digit grouping symbols, etc.

So, if we remove the comma from the above example, we can see that the conversion is successful.

DECLARE @valueToConvert VARCHAR(50);
SET @valueToConvert='1123456.7890';

SELECT CAST(@valueToConvert AS NUMERIC(10,2)) as ConvertedNumber;
GO

Output:

Error converting varchar to numeric in SQL Server - Article on SQLNetHub.com

In general, when converting varchar values to numbers (i.e. decimal, numeric, etc.), you need to be careful in order for your varchar value, not contain any digit grouping symbols (i.e. a comma) or any other characters that do not have a meaning as a number.

Check our Online Courses

  • SQL Server 2022: What’s New – New and Enhanced Features [New]
  • Data Management for Beginners – Main Principles
  • 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

Feel free to check our other relevant articles on SQL Server troubleshooting:

  • Error converting data type varchar to float
  • SQL Server 2022: What’s New – New and Enhanced Features (Course Preview)
  • SQLServerAgent could not be started (reason: Unable to connect to server ‘(local)’; SQLServerAgent cannot start)
  • ORDER BY items must appear in the select list if SELECT DISTINCT is specified
  • There is no SQL Server Failover Cluster Available to Join
  • There is insufficient system memory in resource pool ‘internal’ to run this query.
  • There is not enough space on the disk. (mscorlib)
  • A network-related or instance-specific error occurred while establishing a connection to SQL Server
  • 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
  • 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
  • … all SQL Server troubleshooting articles

Featured Database Productivity 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

Subscribe to our newsletter and stay up to date!

Check out our latest software releases!

Check our eBooks!

Rate this article: 1 Star2 Stars3 Stars4 Stars5 Stars (3 votes, average: 4.33 out of 5)

Loading…

Reference: SQLNetHub.com (https://www.sqlnethub.com)

© SQLNetHub


How to resolve the error: Error converting varchar to numeric in SQL Server

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: 18,900

  • Remove From My Forums
  • Question

  • Good Afternoon,

    I’m trying to convert a field of datatype varchar to numeric and its failing with the following error

    Error converting data type varchar to numeric. Please see the sql am using and the sample data.Please need help!

    SELECT CASE 
           Isnumeric( 
          accela_staging.dbo.fact_highweedsandgrassdetails.vendorinvoiceamount) 
          WHEN 1 THEN Convert(numeric(6,2), dbo.fact_highweedsandgrassdetails.vendorinvoiceamount)
             --CAST(fact_highweedsandgrassdetails.vendorinvoiceamount AS NUMERIC(9,2)) 
         END                                                        AS 
           Total_Dollar_Amount

    VendorInvoiceAmount
    p
    97.50
    84.00
    65.00
    55.00
    420.00
    350.00
    325.00
    325.00
    240.00
    185.00
    182.00
    175.00
    150.00
    150.00
    140.00
    140.00
    135.00
    130.00
    130.00
    125.00
    120.00
    115.00
    104.00
    100.00
    10.00
    0.00
    -65.00
    -65.00
    -55.00
    -55.00
    -50.00
    0.00
    NULL


    SV

Answers

  • Thanks Visakh16, from the link i created a function and executed the sql. Please see the below query and result set. Its showing validty 0 for ‘p’ and ‘NULL’. I can ask the users to correct the «P» record, but «NULL» are valid i cant
    filter them. What is the workaround for that?

    select distinct k.VendorInvoiceAmount,k.valid
    from
    (select CaseNumber,VendorInvoiceAmount, dbo.is_numeric(VendorInvoiceAmount)as valid 
    from dbo.FACT_HighWeedsAndGrassDetails
    )k

    VendorInvoiceAmount	valid
    125.00	1
    240	1
    185.00	1
    -55	1
    130.00	1
    104.00	1
    0	1
    .	1
    100	1
    150.00	1
    p	0
    55	1
    140	1
    130	1
    140.00	1
    -65	1
    182.00	1
    -55.00	1
    NULL	0
    65	1
    84.00	1
    100.00	1
    325	1
    175.00	1
    -0	1
    10	1
    350	1
    97.50	1
    -50	1
    150	1
    120	1
    135.00	1
    115	1
    420.00	1
    -65.00	1
    325.00	1


    SV

    Nope thats not true

    NULL represents an unknown value so you wont be able to determine a data type for it

    Hence validation functions like ISNUMERIC,ISDATE etc should always return false for it

    see this

    SELECT ISNUMERIC(NULL),ISDATE(NULL)

    So the function is working as per design

    if you want to include them too you need to write condition as this

    select distinct k.VendorInvoiceAmount,k.valid
    from
    (select CaseNumber,VendorInvoiceAmount, dbo.is_numeric(VendorInvoiceAmount)as valid 
    from dbo.FACT_HighWeedsAndGrassDetails
    )k
    WHERE valid = 1
    OR VendorInvoiceAmount IS NULL


    Please Mark This As Answer if it solved your issue
    Please Mark This As Helpful if it helps to solve your issue
    Visakh
    —————————-
    My MSDN Page
    My Personal Blog
    My Facebook Page

    • Marked as answer by

      Tuesday, October 28, 2014 3:06 PM

  • case when value NOT
    LIKE ‘%[^0-9]%’ THEN CAST(value
    as numeric(6,2))
    ELSE NULL END

    The values contain ‘.’ which is not 0-9. So no, it should not solve your problem, unless the values are not decimal.

    • Marked as answer by
      saivenkat77
      Tuesday, October 28, 2014 3:05 PM

  • Remove From My Forums
  • Question

  • HELLO

    i am trying to use the following code to convert varchar to numeric but i am getting error so tell me where i am wrong

    insert AST.dbo.APPOINTMENTTYPE

     (DESCRIPTION, CREATEDTTM,CREATEUSERID,MODIFYDTTM, MODIFYUSERID,APPOINTMENTTYPEID) 

    select DESCRIPTION,DATE_CREATED,CREATED_BY,DATE_MODIFIED,MODIFIED_BY,CAST(APPT_TYPE_CODE AS NUMERIC(10,0)) AS APPOINTMENTTYPEID

     FROM ASTP.dbo.A_APPT_TYPES

    APPT_TYPE_CODE IS A COLUMN which i am trying to convert to numeric .

    Actually i am trying to put that column to other table in different DB in the same instance.

    Tell me where i am wrong

    Thanks


    dimrd_SQL

    • Moved by

      Monday, December 20, 2010 9:50 AM
      move to an appropriate forum (From:SQL Server Migration)

Answers

  • HELLO

    i am trying to use the following code to convert varchar to numeric but i am getting error so tell me where i am wrong

    insert AST.dbo.APPOINTMENTTYPE

     (DESCRIPTION, CREATEDTTM,CREATEUSERID,MODIFYDTTM, MODIFYUSERID,APPOINTMENTTYPEID) 

    select DESCRIPTION,DATE_CREATED,CREATED_BY,DATE_MODIFIED,MODIFIED_BY,CAST(APPT_TYPE_CODE AS NUMERIC(10,0)) AS APPOINTMENTTYPEID

     FROM ASTP.dbo.A_APPT_TYPES

    APPT_TYPE_CODE IS A COLUMN which i am trying to convert to numeric .

    Actually i am trying to put that column to other table in different DB in the same instance.

    Tell me where i am wrong

    Thanks


    dimrd_SQL

    Hi,

    Could you please post the error message you received and the table DDLs? You may experience different errors when converting varchar values to numeric values.

    For example,

    DECLARE @v varchar(100)
    SET @v = 'a123'
    SELECT CONVERT(numeric(18,2),@v)
    
    --Error:
    --Msg 8114, Level 16, State 5, Line 11
    --Error converting data type varchar to numeric.
    
    DECLARE @v varchar(100)
    
    SET @v = '1234'
    SELECT CONVERT(numeric(5,2),@v)
    
    --Error:
    --Msg 8115, Level 16, State 8, Line 5
    --Arithmetic overflow error converting varchar to data type numeric.

    For the second error, if we declare a numeric(5,2) variable, it can only hold three (5-2) digits before the decimal point. However, “1234” has four digits before the decimal point so it exceeds the precision.

    For more details, please see:

    decimal and numeric (Transact-SQL)
    http://msdn.microsoft.com/en-us/library/ms187746.aspx


    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.

    • Proposed as answer by
      Naomi N
      Monday, December 20, 2010 3:16 PM
    • Marked as answer by
      KJian_
      Thursday, December 23, 2010 6:59 AM

  • There could be some records in ASTP.dbo.A_APPT_TYPES where
    APPT_TYPE_CODE is not convertable into numeric.

    Check for;

    select APPT_TYPE_CODE AS APPOINTMENTTYPEID
    FROM ASTP.dbo.A_APPT_TYPES
    WHERE ISNUMERIC(APPT_TYPE_CODE) = 0
    

    Update the records with valid numeric value.


    Please visit my Blog for some easy and often used t-sql scripts

    • Proposed as answer by
      Naomi N
      Monday, December 20, 2010 3:16 PM
    • Marked as answer by
      KJian_
      Thursday, December 23, 2010 6:59 AM

Содержание

  1. Mssql error converting data type varchar to numeric
  2. Answered by:
  3. Question
  4. Answers
  5. All replies
  6. Mssql error converting data type varchar to numeric
  7. Answered by:
  8. Question
  9. Answers
  10. All replies
  11. Mssql error converting data type varchar to numeric
  12. Answered by:
  13. Question
  14. Answers
  15. All replies

Mssql error converting data type varchar to numeric

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

Answered by:

Question

I’m trying to convert a field of datatype varchar to numeric and its failing with the following error

Error converting data type varchar to numeric. Please see the sql am using and the sample data.Please need help!

Answers

Thanks Visakh16, from the link i created a function and executed the sql. Please see the below query and result set. Its showing validty 0 for ‘p’ and ‘NULL’. I can ask the users to correct the «P» record, but «NULL» are valid i cant filter them. What is the workaround for that?

Nope thats not true

NULL represents an unknown value so you wont be able to determine a data type for it

Hence validation functions like ISNUMERIC,ISDATE etc should always return false for it

So the function is working as per design

if you want to include them too you need to write condition as this

Please Mark This As Answer if it solved your issue
Please Mark This As Helpful if it helps to solve your issue
Visakh
—————————-
My MSDN Page
My Personal Blog
My Facebook Page

case when value NOT LIKE ‘%[^0-9]%’ THEN CAST ( value as numeric ( 6 , 2 )) ELSE NULL END

The values contain ‘.’ which is not 0-9. So no, it should not solve your problem, unless the values are not decimal.

There isn’t anything fundamentally wrong with what you did:

Both of these queries run just fine.

Can you provide the full DDL, DML and any attached objects (triggers et al)? There maybe some clues there.

Yup, it’s an invalid SQL SELECT statement. E.g. as a stand-alone example

This should run in your environment:

Thanks Patrick, below is the complete query

SV, scientific notation would cause this issue. For instance, ‘3.12332E10’ would succeed the test of the isnumeric function but would fail to convert. It happens almost everytime I import from excel.

Look for values containing ‘E’. If it is not your case then I would suggest doing a dichotonic search to figure out the failing value (split the result in half until you find the error).

To illustrate what I just said

Without example data from all of those objects, we won’t be able to test the full query for you. If you are sure the problem is on the original line you posted, we’d need to see any other objects associated with that column. Are there any triggers on the table?

Also, try aliasing your tables, to make referencing them quicker and easier (and improving the readability of your code). Aliasing works like this:

SV, I believe I had this issue with scientific notation. For instance, ‘3.12332E10’ would succeed the test of the isnumeric function but would fail to convert.

Look for values containing ‘E’. If it is not your case then I would suggest doing a dichotonic search to figure out the failing value (split the result in half until you find the error).

Actually, numbers even as large as 1234567890123456789012345678.00 convert to numeric from varchar, without an issue:

Since the original convert was only to 6, if any number larger than 999999.99 was encountered, it would have generated an overflow error.

Like you observed i have maany calculations in the sql. I zeroed on this particular «total_dollar_amount» calculation by commenting it out and re running the query and it worked fine. The problem is with this conversion only.There are no other objects that are associated with column and NO there are no triggers either.

No, negative values won’t cause a problem.

However, currency signs can. If you’re using SQL Server 2012 or newer, you can use TRY_CONVERT:

This should return all rows which cannot be converted.

SV, I believe I had this issue with scientific notation. For instance, ‘3.12332E10’ would succeed the test of the isnumeric function but would fail to convert.

Look for values containing ‘E’. If it is not your case then I would suggest doing a dichotonic search to figure out the failing value (split the result in half until you find the error).

Actually, numbers even as large as 1234567890123456789012345678.00 convert to numeric from varchar, without an issue:

Since the original convert was only to 6, if any number larger than 999999.99 was encountered, it would have generated an overflow error.

Источник

Mssql error converting data type varchar to numeric

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

Answered by:

Question

I am getting following error when I am trying to insert data into target table.
«Error converting data type varchar to numeric.»

so I tried to debug by inserting few number of rows to find out if there is a problem in data. But when I tried to divide data and insert the data, it is inserting and not giving any error. But when I try to insert large volume of data it is giving above error.

Please needed urgently

Answers

We don’t know much about your INSERT statement, but from what you say, it sounds like this is a «false» error. That is, it is an error that occurs with data that is supposed to be filtered out by the WHERE clause in your SELECT statement, but because SQL Server recasts computation order from the logical order, the error occurs. However, when you try to divide and conquer, the optimizer outsmarts you by choosing a different plan which does not have this problem.

As Tom says, TRY_CAST/TRY_CONVERT is the easiest way out.

Regards, Muthukumar Balu

i think your trying to insert records from varchar or char column to INT column

when you check the fewer column may be that data set may only contain the data that can the implicit convert to int

a good may be to find the incorrect data and fix it, below query may help you to start with

Thanks Saravana Kumar C

You will get much better help if you post the INSERT statement that is getting this error. If you are on SQL 2012 or later, I would recommend you use either the TRY_CAST or TRY_CONVERT function to change the data from varchar to numeric.

We don’t know much about your INSERT statement, but from what you say, it sounds like this is a «false» error. That is, it is an error that occurs with data that is supposed to be filtered out by the WHERE clause in your SELECT statement, but because SQL Server recasts computation order from the logical order, the error occurs. However, when you try to divide and conquer, the optimizer outsmarts you by choosing a different plan which does not have this problem.

As Tom says, TRY_CAST/TRY_CONVERT is the easiest way out.

I am getting following error when I am trying to insert data into target table.
«Error converting data type varchar to numeric.»

so I tried to debug by inserting few number of rows to find out if there is a problem in data. But when I tried to divide data and insert the data, it is inserting and not giving any error. But when I try to insert large volume of data it is giving above error.

It may be that the offending data is coming in later batches so initial batches might have loaded fine

The main places you need to focus are the cases where you try to populate decimal,numeric data from character based source. Make sure the source field does not have any characters which makes it an invalid numeric data. If you’re doing an implicit conversion make sure you tidy the data out to valid numeric format before you apply cast or convert or it .In case you’re on 2012 version you can apply TRY_CAST or TRY_CONVERT which will not raise it as an error but just returns a NULL in case of conversion error.

Please Mark This As Answer if it solved your issue
Please Vote This As Helpful if it helps to solve your issue
Visakh
—————————-
My Wiki User Page
My MSDN Page
My Personal Blog
My Facebook Page

Источник

Mssql error converting data type varchar to numeric

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

Answered by:

Question

I have created a stored procedure where I am collecting data against input phone number.

STORED PROCEDURE:

USE [CCCust_StoreData]
GO
/****** Object: StoredProcedure [dbo].[sp_StoreData] Script Date: 12/29/2014 08:44:14 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

EXEC [sp_StoreData] ‘01217645142’

ALTER PROCEDURE [dbo].[sp_StoreData](@DNIS_NO varchar(255)) AS

/*
This procedure returns key value pairs containg the store info based on a lookup in the STOREDATA_CUSTPLANT database tables
*/

DECLARE @recCnt int,
@matchrec int,
@intTelNo NUMERIC(21,0),
@retString varchar(800)

IF isNumeric(@DNIS_NO) != 1
BEGIN
SELECT ‘STORE_NUMBER:|STORE_NAME:|PLANT:’
RETURN
END

SET @recCnt = 0
SET @intTelNo = CAST(@DNIS_NO AS NUMERIC(21,0))

SELECT @recCnt = COUNT(DISTINCT MP.STORE_NUMBER)
FROM STOREDATA_CUSTPLANT MP
WHERE CAST(‘0’+MP.PHONE_NUMBER AS NUMERIC(21,0)) = @intTelNo

IF @recCnt > 0
BEGIN
— If only one record matches — return the info
SELECT TOP 1 ‘STORE_NUMBER:’ + CAST(@recCnt AS VARCHAR) + ‘|STORE_NAME:’ + ISNULL(MP.STORE_NAME, ») + ‘|PLANT:’ + ISNULL(MP.PLANT, »)
FROM [STOREDATA_CUSTPLANT] MP

WHERE CAST(‘0’+MP.PHONE_NUMBER AS NUMERIC(21,0)) = @intTelNo

RETURN
END
ELSE
BEGIN
SELECT ‘STORE_NUMBER:|STORE_NAME:|CONTACT_ID:|PLANT:’
RETURN
END

Data Types:

STORE_NUMBER data type is set on table is varchar(50)
STORE_NAME data type is set on table is varchar(50)
PLANT data type is set on table is varchar(50)
PHONE_NUMBER data type is set on table is varchar(50)

When I try to execute sp_StoreData, I get the following error:

Msg 8114, Level 16, State 5, Procedure sp_StoreData, Line 30
Error converting data type varchar to numeric.

Can someone please help me.

Answers

Stored Procedure is OK. However, table did contain some wrong record which cause error in handling the query.

  • Marked as answer by Lydia Zhang Microsoft contingent staff Thursday, January 1, 2015 7:35 AM

Please Mark This As Answer if it solved your issue
Please Vote This As Helpful if it helps to solve your issue
Visakh
—————————-
My Wiki User Page
My MSDN Page
My Personal Blog
My Facebook Page

  • Edited by Visakh16 MVP Monday, December 29, 2014 1:30 PM
  • Proposed as answer by Tom Phillips Monday, December 29, 2014 2:43 PM

Balmukund Lakhani
Please mark solved if I’ve answered your question, vote for it as helpful to help other users find a solution quicker
———————————————————————————
This posting is provided «AS IS» with no warranties, and confers no rights.
———————————————————————————
My Blog | Team Blog | @Twitter | Facebook
Author: SQL Server 2012 AlwaysOn — Paperback, Kindle

Yes, you are right.

Table have following data:

STORE_NUMBER STORE_NAME PLANT PHONE_NUMBER
50002430 ALDI ACOCKS GREEN (12) UU19 01217645142
50011339 ALDI ALFRETON (62) UU19 01773540874
50007706 ALDI ASHBY DE LA ZOUCH (91) UU19 01530560629

due to round brackets in STORE_NAME, error occurs.

Can you please tell me how I can solve this issue ? what data type I can set to solve this.

This should reveal the columns with bad data.

Don’t name your procedure sp_ as sp_ prefix is reserved for MS (system) stored procedures. Any other prefix will be OK, just not ‘sp_’

Also, ISNUMERIC doesn’t filter non-numeric items as it’s a wide spec function. If you’re using SQL 2012 and up, I suggest to use TRY_CAST function instead.

Check this blog post

For every expert, there is an equal and opposite expert. — Becker’s Law

>> I have created a stored procedure where I am collecting data against input phone number. and not the C family !=. Why did you use the magical VARCHAR(50) default for everything? Old ACCESS programmers make that mistake. We also gave up camelCase years ago; it does not work and will increase the time to maintain code.

But the error that makes RDBMS people laugh is a numeric telephone number. Are you going to take a square root of a phone number? And it can be FIFTY characters long?

This is not how to use SQL or RDBMS. If this were a carpentry forum, you would be the guy who is trying to saw wood with a screwdriver.

Read the E.123 Standards for phone numbers and write a CHECK() constraint on a column based on it. I find it is better to get a data scrubbing tool and let it format and validate phone numbers instead of wasting time to write my own.

—CELKO— Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking in Sets / Trees and Hierarchies in SQL

Источник

54 / 6 / 5

Регистрация: 24.01.2019

Сообщений: 171

1

23.02.2021, 22:08. Показов 11822. Ответов 24


Делаю UPDATE таблицы Orders, конкретно поле Price(decimal) изPrice.Text, получаю:
Ошибка при преобразовании типа данных varchar к numeric.
Проблема в том что, в этом поле число с запятой, если запятую убирать то «обновляшка» срабатывает, но я же не могу цену в целочисленном типе писать.
Как это победить ?

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Igr_ok

783 / 615 / 272

Регистрация: 04.08.2015

Сообщений: 1,707

23.02.2021, 22:33

2

7-2-3, вот тут MsGuns расписал, как не надо кодить, вам это тоже полезно Добавление записи в таблицу

Цитата
Сообщение от 7-2-3
Посмотреть сообщение

Price.Text

Если Price — это текстбокс, то откройте для себя другие контролы, которые позволяют работать с числами, датой и т.д. Для чисел — NumericUpDown https://docs.microsoft.com/en-… ew=net-5.0
Запрос пишете с параметрами, добавляя параметр так:

C#
1
command.Parameters.AddWithValue(@Price, numericUpDown1.Value);



1



54 / 6 / 5

Регистрация: 24.01.2019

Сообщений: 171

23.02.2021, 23:04

 [ТС]

3

Так это он мне и написал)



0



1496 / 1238 / 244

Регистрация: 04.04.2011

Сообщений: 4,356

23.02.2021, 23:23

4

Цитата
Сообщение от 7-2-3
Посмотреть сообщение

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

Обратите внимание на Decimalseparator https://docs.microsoft.com/en-… ew=net-5.0

Добавлено через 2 минуты
И просто интересно — Вы в какой стране живете, что у вас копейки есть в ценах ?



0



54 / 6 / 5

Регистрация: 24.01.2019

Сообщений: 171

24.02.2021, 08:50

 [ТС]

5

В России, копейки сами по себе конечно не очень нужны, только при расчёте НДС.



0



7-2-3

54 / 6 / 5

Регистрация: 24.01.2019

Сообщений: 171

24.02.2021, 10:39

 [ТС]

6

Поставил вместо текстбокса:

C#
1
+ "',Price='" + numericUpDown1+

Прикрутил параметр:

C#
1
myCommand.Parameters.AddWithValue("@Price", numericUpDown1.Value);

Теперь немного другое сообщение получаю:

C#
1
2
3
Ошибка арифметического переполнения при преобразовании varchar к типу данных numeric.
 
Выполнение данной инструкции было прервано.

Миниатюры

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



0



7-2-3

54 / 6 / 5

Регистрация: 24.01.2019

Сообщений: 171

24.02.2021, 10:50

 [ТС]

7

NumberFormatInfo-эта штуковина, которая позволяет обходить проблемы с точками и запятыми(которые ещё в региональных настройках сидят) ?

Добавлено через 4 минуты
Попробовал

C#
1
+ "',Price='" + numericUpDown1.Value+

Получил первоначальное сообщение.
Ошибка при преобразовании типа данных varchar к numeric.

Добавлено через 5 минут
Попробовал numericUpDown1.DecimalPlaces, но он мне количество знаков после запятой и показывает, т.е. «2»



0



Andrey-MSK

1372 / 883 / 206

Регистрация: 14.08.2018

Сообщений: 2,822

Записей в блоге: 3

24.02.2021, 12:03

8

7-2-3, в SQL (MS SQL) строки присваиваются так:

T-SQL
1
SET TextField = 'SomeText'

а числа так:

T-SQL
1
SET NumField = 45.89

Разницу со своей записью видите?



0



783 / 615 / 272

Регистрация: 04.08.2015

Сообщений: 1,707

24.02.2021, 12:10

9

7-2-3, я не вижу на вашем скрине запроса с параметрами. И лучше подкрепляйте свои сообщения кодом(а не скрином), так проще указать на ошибки.



0



7-2-3

54 / 6 / 5

Регистрация: 24.01.2019

Сообщений: 171

24.02.2021, 12:16

 [ТС]

10

Вот, мой красивый и замечательный кодик:

C#
1
2
3
 SqlCommand myCommand = conn.CreateCommand();
                myCommand = new SqlCommand("UPDATE Orders SET  ProductID='" + ProductID.Text + "',Qty='" + Qty.Text + "',Price='" + numericUpDown1.Value + "' WHERE OrderID='" + OrderID + "' AND LineItem='" + LineItem + "' ", conn);
                myCommand.Parameters.AddWithValue("@Price", numericUpDown1.Value);



0



Andrey-MSK

1372 / 883 / 206

Регистрация: 14.08.2018

Сообщений: 2,822

Записей в блоге: 3

24.02.2021, 12:29

11

Цитата
Сообщение от 7-2-3
Посмотреть сообщение

C#
1
myCommand.Parameters.AddWithValue("@Price", numericUpDown1.Value);

И где в запросе вот этот параметр? И все остальные тоже



0



MsGuns

1496 / 1238 / 244

Регистрация: 04.04.2011

Сообщений: 4,356

24.02.2021, 13:01

12

C#
1
2
3
4
5
6
7
myCommand = new SqlCommand("UPDATE Orders SET  ProductID=@product, Qty=@quant, Price=@price " +
              "WHERE OrderID=@orderid AND LineItem=@lineitem", conn);
myCommand.Parameters.AddWithValue("@product", Int32(ProductID.Text));
myCommand.Parameters.AddWithValue("@quant", Int32(Qty.Text));
myCommand.Parameters.AddWithValue("@price", numericUpDown1.Value);
myCommand.Parameters.AddWithValue("@orderid", Int32(OrderID));
myCommand.Parameters.AddWithValue("@lineitem", LineItem);



1



54 / 6 / 5

Регистрация: 24.01.2019

Сообщений: 171

25.02.2021, 14:12

 [ТС]

13

Если бы не Price, то моя «обновляшка» бы и без параметров сработала.
Ну я же примерно то же самое в своём коде написал, параметр для Price указать был, остальные просто не стал впихивать.

Но в итоге, VS не нравится это:

Миниатюры

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



0



Andrey-MSK

1372 / 883 / 206

Регистрация: 14.08.2018

Сообщений: 2,822

Записей в блоге: 3

25.02.2021, 15:35

14

7-2-3, параметры можно объявлять по другому, это более полная запись, тут явно всё указывается — тип, значения, направление параметра:

C#
1
2
3
4
5
6
7
8
                    SqlParameter param = new SqlParameter
                    {
                        ParameterName = "@idDraw",
                        Value = drawID,
                        SqlDbType = SqlDbType.Int,
                        Direction = ParameterDirection.Input
                    };
                    sqlCommand.Parameters.Add(param);

Добавлено через 2 минуты
7-2-3, и преобразование типов в DataReader:

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
                    using (SqlDataReader dataReader = sqlCommand.ExecuteReader())
                    {
                        while (dataReader.Read())
                        {
                            draw.IDDraw = (int)dataReader["ID_Draw"];
                            draw.IDGenPlan = (int)dataReader["ID_GenPlan"];
                            draw.DrawNum = dataReader["DrawNum"] as string ?? "";
                            draw.DrawName = dataReader["DrawName"] as string ?? "";
                            draw.Stage = dataReader["Stage"] as string ?? "";
                            draw.StageTEP = (int)dataReader["StageTEP"];
                            draw.Works = dataReader["Works"] as string ?? "";
                        }
                    }



1



Igr_ok

783 / 615 / 272

Регистрация: 04.08.2015

Сообщений: 1,707

25.02.2021, 17:54

15

7-2-3, вместо

Цитата
Сообщение от MsGuns
Посмотреть сообщение

C#
1
Int32(ProductID.Text)

надо писать
ConvertToInt32(ProductID.Text) или (int)ProductID.Text.



0



1496 / 1238 / 244

Регистрация: 04.04.2011

Сообщений: 4,356

25.02.2021, 18:40

16

Igr_ok, Я в курсе: копипаста подвела + невнимательность



0



54 / 6 / 5

Регистрация: 24.01.2019

Сообщений: 171

25.02.2021, 19:46

 [ТС]

17

Я видимо что то не так делаю:

Миниатюры

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



0



1496 / 1238 / 244

Регистрация: 04.04.2011

Сообщений: 4,356

25.02.2021, 23:24

18

Цитата
Сообщение от 7-2-3
Посмотреть сообщение

Я видимо что то не так делаю:

«Слепая» копипаста Откуда было известно как называются боксы Вашей формы, из которых извлекаются значения параметров. Вот и получили названия «по смыслу», теперь вместо них подставьте Ваши излюбленные TextBox298, TexBox100500 и т.д.



0



54 / 6 / 5

Регистрация: 24.01.2019

Сообщений: 171

26.02.2021, 10:23

 [ТС]

19

А вот и нет, я именно проименовал текстбоксы. ProductID.Text(и т.п.), оно так и было.



0



MsGuns

1496 / 1238 / 244

Регистрация: 04.04.2011

Сообщений: 4,356

26.02.2021, 13:05

20

Скобки уберите вокруг ProductID.Text:

C#
1
  myCommand.Parameters.AddWithValue("@product", (int)ProductID.Text);



0



SQL Arithmetic Overflow Error Converting Varchar to Data Type Numeric

The Arithmetic Overflow Error occurs when converting a numeric or decimal value into a varchar data type, either implicitly or explicitly, and the length of the varchar variable or column is not long enough to hold the decimal or numeric value.

Example Query :

CREATE TABLE CARS(CID INT NOT NULL, CNAME VARCHAR(15),
CCOST DECIMAL(5,4) DEFAULT ‘15000.1234’);

INSERT INTO CARS(CID,CNAME) VALUES(123,’BOLERO’);
SELECT*FROM CARS;

—DROP TABLE CARS;

Msg 8115, Level 16, State 8, Line 1

Arithmetic overflow error converting varchar to data type numeric.

The statement has been terminated.

Numeric data types that have fixed precision and scale decimal [(p[,s])] and numeric[(p[,s])].

When maximum precision is used, valid values are from — 10^38 +1 through 10^38 — 1. 

The ISO synonyms for decimal are dec and dec(p, s). numeric is functionally equivalent to decimal.

The maximum total number of decimal digits that will be stored, both to the left and to the right of the decimal point. 

The precision must be a value from 1 through the maximum precision of 38. The default precision is 18.

The no. of decimal digits that will be stored to the right of the decimal point. This number is subtracted from p to determine the maximum number of digits to the left of the decimal point. 

Scale must be a value from 0 through p. Scale can be specified only if precision is specified. The default scale is 0; therefore, 0 <= s <= p. Maximum storage sizes vary, based on the precision.

Converting decimal and numeric Data :

For the decimal and numeric data types, SQL Server considers each specific combination of precision and scale as a different data type. For example, decimal(5,5) and decimal(5,0) are considered different data types.

In Transact-SQL statements, a constant with a decimal point is automatically converted into a numeric data value, using the minimum precision and scale necessary. For example, the constant 12.345 is converted into a numeric value with a precision of 5 and a scale of 3.

Converting from decimal or numeric to float or real can cause some loss of precision. Converting from int, smallint, tinyint, float, real, money, or smallmoney to either decimal or numeric can cause overflow.

By default, SQL Server uses rounding when converting a number to a decimal or numeric value with a lower precision and scale. However, if the SET ARITHABORT option is ON, SQL Server raises an error when overflow occurs. Loss of only precision and scale is not sufficient to raise an error.
When converting float or real values to decimal or numeric, the decimal value will never have more than 17 decimals. Any float value < 5E-18 will always convert as 0. 


Resolved Query :

CREATE TABLE CARS(CID INT NOT NULL,CNAME VARCHAR(15),

CCOST DECIMAL(9,4) DEFAULT ‘15000.1234’);

INSERT INTO CARS(CID,CNAME) VALUES(123,’BOLERO’);

#—————————————————————Thanks—————————————————————#

Понравилась статья? Поделить с друзьями:
  • Ms xbl multiplayer ошибка
  • Ms windows store purgecaches ошибка файловой системы 2147416359
  • Ms visual database tools error
  • Ms sql ошибка 2146885628
  • Ms sql ошибка 1222