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

I am getting the same error when i execute the below code,
  • Remove From My Forums
  • Question

  • I am getting the same error when i execute the below code,

    DECLARE @GrossClaimAmountEuro NVARCHAR(1000)
    SELECT @GrossClaimAmountEuro = SUBSTRING(RTRIM(LTRIM(TempColumn)),0,LEN(RTRIM(LTRIM(TempColumn))) — LEN(‘Total Disputed Invoice Value’))
    FROM fn_CCT_ConvertTextToRows(‘Customer Name               : SPORT DANMARK A/S
             Sold To #                   : 117799
             Total Claim Value           : 170,000.00
             Total Disputed Invoice Value: 170,000.00
             Total Claim Units           : 13
             Currency                    : EUR’)
    WHERE RTRIM(LTRIM(TempColumn)) like ‘%Total Disputed Invoice Value%’
     IF ISNUMERIC(@GrossClaimAmountEuro) = 0
      SET @GrossClaimAmountEuro = ‘0’

     SET @GrossClaimAmountEuro = REPLACE(@GrossClaimAmountEuro,’,’,»)
    SELECT @GrossClaimAmountEuro
    SELECT CONVERT(DECIMAL(15,4),LTRIM(RTRIM(‘170000.00          ‘)))
    SELECT CONVERT(DECIMAL(15,4),LTRIM(RTRIM(@GrossClaimAmountEuro)))

    The variable @GrossClaimAmountEuro  holds holds a value ‘170000.00          ‘. When i hardcode the value and execute, the code works fine, if i give the variable name in the code, i am getting a error as,
    «Msg 8114, Level 16, State 5, Line 18
    Error converting data type nvarchar to numeric.»

    I dont know..  what i am doing wrong..
    Please help

Answers

  • I got the problem solved, the variable was having some juck characters. I replaced it using ASCII code. Thank you all for the support.

    • Marked as answer by

      Wednesday, July 29, 2009 8:52 AM

I have table1 with two columns:

  • col1 - nvarchar(510)
  • col2 - nvarchar(510)

I want to take all the values from table1 and put it to table2 where data type is different:

  • col1_A - numeric(22,10)
  • col2_A - int

I’m doing like:

insert into table2 
    select cast(col1 as numeric), cast(col2 as int)

but I’m getting error:

enter image description here

What is wrong?

marc_s's user avatar

marc_s

722k173 gold badges1321 silver badges1443 bronze badges

asked Aug 18, 2016 at 14:55

4est's user avatar

1

You probably have a character in table1.col1. Also, it’s important to point out that table1.col1 is nvarchar(510) but if len(table1.col1) > 11 you are going to get an Arithmetic overflow error.

declare @char nvarchar(510)
set @char = '123456789101'
--set @char = '1234567891011'   --will cause an arithmetic overflow error since you are using numeric(22,10)
--set @char = '123abc456'       --will cause Error converting data type nvarchar to numeric

declare @num numeric(22,10)
set @num = cast(@char as numeric(22,10))

select @num

answered Aug 18, 2016 at 15:04

S3S's user avatar

S3SS3S

24.7k5 gold badges24 silver badges44 bronze badges

2

It means you need to sanitize your data. Find which values are causing the issue and then manually correct them first or exclude them. To find which values are not numeric use the ISNUMERIC function.

select col1 
from yourtable 
where ISNUMERIC(col1) = 0

marc_s's user avatar

marc_s

722k173 gold badges1321 silver badges1443 bronze badges

answered Aug 18, 2016 at 15:04

Igor's user avatar

IgorIgor

59.8k10 gold badges94 silver badges168 bronze badges

5

thank you Eric for help to find wrong recrods!
I did case as below:

case
 when [col1] LIKE '%,%' then REPLACE([col1]),',','')
else  CAST([col1] as Numeric)
end

and it’s working!

answered Aug 18, 2016 at 15:48

4est's user avatar

4est4est

2,8206 gold badges33 silver badges61 bronze badges

I have table1 with two columns:

  • col1 - nvarchar(510)
  • col2 - nvarchar(510)

I want to take all the values from table1 and put it to table2 where data type is different:

  • col1_A - numeric(22,10)
  • col2_A - int

I’m doing like:

insert into table2 
    select cast(col1 as numeric), cast(col2 as int)

but I’m getting error:

enter image description here

What is wrong?

marc_s's user avatar

marc_s

722k173 gold badges1321 silver badges1443 bronze badges

asked Aug 18, 2016 at 14:55

4est's user avatar

1

You probably have a character in table1.col1. Also, it’s important to point out that table1.col1 is nvarchar(510) but if len(table1.col1) > 11 you are going to get an Arithmetic overflow error.

declare @char nvarchar(510)
set @char = '123456789101'
--set @char = '1234567891011'   --will cause an arithmetic overflow error since you are using numeric(22,10)
--set @char = '123abc456'       --will cause Error converting data type nvarchar to numeric

declare @num numeric(22,10)
set @num = cast(@char as numeric(22,10))

select @num

answered Aug 18, 2016 at 15:04

S3S's user avatar

S3SS3S

24.7k5 gold badges24 silver badges44 bronze badges

2

It means you need to sanitize your data. Find which values are causing the issue and then manually correct them first or exclude them. To find which values are not numeric use the ISNUMERIC function.

select col1 
from yourtable 
where ISNUMERIC(col1) = 0

marc_s's user avatar

marc_s

722k173 gold badges1321 silver badges1443 bronze badges

answered Aug 18, 2016 at 15:04

Igor's user avatar

IgorIgor

59.8k10 gold badges94 silver badges168 bronze badges

5

thank you Eric for help to find wrong recrods!
I did case as below:

case
 when [col1] LIKE '%,%' then REPLACE([col1]),',','')
else  CAST([col1] as Numeric)
end

and it’s working!

answered Aug 18, 2016 at 15:48

4est's user avatar

4est4est

2,8206 gold badges33 silver badges61 bronze badges

54 / 6 / 5

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

Сообщений: 171

1

23.02.2021, 22:08. Показов 11861. Ответов 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

1377 / 888 / 205

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

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

Записей в блоге: 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

1377 / 888 / 205

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

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

Записей в блоге: 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

1377 / 888 / 205

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

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

Записей в блоге: 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



You can’t easily control the order in which SQL Server will evaluate the contents of a column that does not use the correct data type (or has mismatched precision). If you try to cast a column that is nvarchar to numeric, even if you have filters that should eliminate all non-numeric values from consideration, SQL Server can still try those first (see Erland’s complaint about this on UserVoice). There are cases where you can nest CTEs until the cows come home, but SQL Server will still push or pull that evaluation to a place where you didn’t expect it.

As long as aggregates and fulltext functions aren’t involved (see here and here), you can force this evaluation before conversion by using a CASE expression. Here is a simplified version of your query with no CTEs:

SELECT cfv.issue,
  priority_num = CONVERT(NUMERIC(something, something), 
    CASE WHEN ISNUMERIC(cfo.customvalue)=1 THEN cfo.customvalue END)
FROM
  proddb1.customfieldvalue AS cfv
  INNER JOIN proddb1.customfield AS cf
  ON cfv.CUSTOMFIELD = cf.id
  INNER JOIN proddb1.customfieldoption AS cfo
  ON cfv.CUSTOMFIELD = cfo.CUSTOMFIELD
  AND CONVERT(NUMERIC(something, something), 
    CASE WHEN ISNUMERIC(cfo.customvalue)=1 THEN cfo.customvalue END) = cfo.id
  WHERE cf.cfname = 'Issue Priority';

You will need to change something, something to the proper precision/scale (or use one of the int types if you don’t need decimal places). You should never declare varying types without specifying the length — this blog post is about varchar, but it really applies to all of the types.

If you are on SQL Server 2012 (it’s always useful to include information like what version of SQL Server you’re using), you can simplify this:

CONVERT(NUMERIC(something, something), 
    CASE WHEN ISNUMERIC(cfo.customvalue)=1 THEN cfo.customvalue END)

to this:

TRY_CONVERT(NUMERIC(something, something), cfo.customvalue)

And it will actually be more reliable (since ISNUMERIC can return 1 and still fail at conversion time for specific types). I blogged about this way back in 2002.

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

  • Hello and thank you for reading.
    I got ‘Error converting data type nvarchar to numeric’ for the EXPR element.
    How can I select the decimal EXPR element from the xml? FYI: The target column named similar EXPR is datatype decimal (18,2)

    DECLARE @xml XML
    SELECT @xml = x.y
    FROM OPENROWSET( BULK 'C:File.xml', SINGLE_CLOB ) x(y)
    INSERT INTO dbo.Product( LITM,EXPR )
    SELECT 
    	x.y.value('(LITM/text())[1]', 'VARCHAR(MAX)') AS LITM,
    	x.y.value('(price/EXPR/text())[1]', 'decimal') AS EXPR
    FROM @xml.nodes('prices/item') AS x(y)
    

    Thank you

    • Изменено

      11 июня 2011 г. 14:35
      formatted

Ответы

  • With that particular piece of XML and table then it does work, eg

    DECLARE @xml XML
    
    SET @xml = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <prices>
    	<message_header source="Alltron AG" message_type="price" document_version_date="26.02.2009" document_version="1.00" generation_date="11.06.2011" generation_time=" 4:41:43"/>
    	<item>
    		<LITM>1028</LITM>
    		<price>
    			<INPR>4.05</INPR>
    			<EXPR>3.75</EXPR>
    			<VATR>8</VATR>
    			<ECPR>23.9</ECPR>
    			<DPPR>7</DPPR>
    		</price>
    	</item>
    	<item>
    		<LITM>1116</LITM>
    		<price>
    			<INPR>42.65</INPR>
    			<EXPR>39.49</EXPR>
    			<VATR>8</VATR>
    			<ECPR>52</ECPR>
    			<DPPR>45.55</DPPR>
    		</price>
    	</item>
    	<item>
    		<LITM>1227</LITM>
    		<price>
    			<INPR>4.75</INPR>
    			<EXPR>4.4</EXPR>
    			<VATR>8</VATR>
    			<ECPR>6.9</ECPR>
    			<DPPR>5.4</DPPR>
    		</price>
    	</item>
    </prices>'
     
    DECLARE @Product TABLE
    	(
    	[LITM] [nvarchar](max) NULL,
    	[EAN] [nvarchar](max) NULL,
    	[Descr] [nvarchar](max) NULL,
    	[MITM] [nvarchar](max) NULL,
    	[EXPR] [decimal](18, 2) NULL
    	)
    
    INSERT INTO @product ( LITM, EXPR )
    SELECT 
    	x.y.value('(LITM/text())[1]', 'NVARCHAR(MAX)') AS LITM,
    	x.y.value('(price/EXPR/text())[1]', 'DECIMAL(18,2)') AS EXPR
    FROM @xml.nodes('prices/item') AS x(y)
    
    SELECT * FROM @Product
    GO
    

    Are you sure that’s the XML and table you are actually using?

    • Помечено в качестве ответа
      zipfeli
      14 июня 2011 г. 14:17

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,939

i m making a registration form… where i want the should go in data table according to choice selected by user…
but when i click the «submit» button. it shows me an error like this…

Server Error in '/project@water_billing_system' Application.

Error converting data type nvarchar to numeric.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.Data.SqlClient.SqlException: Error converting data type nvarchar to numeric.

Source Error: 


Line 521:            cmd.Parameters.Add(prm_ac_code_password);
Line 522:
Line 523:            cmd.ExecuteNonQuery();
Line 524:            conn.Close();
Line 525:        }

Source File: f:water billing systemproject@water_billing_systemonline_redistration.aspx.cs    Line: 523 

i m using stored procedure for this…
and the store procedure is like below.

Quote:

@registration_datetime datetime,
@ac_code_id varchar(8),
@ac_password varchar(max),
@owner_surname varchar(30),
@owner_first_name varchar(30),
@owner_middle_name varchar(30),
@owner_DOB date,
@add_of_c_industry varchar(MAX),
@handler1_name varchar(50),
@handler1_mobile numeric(14,0),
@handler1_landline numeric(18,0),
@handler1_email varchar(50),
@handler2_name varchar(50),
@handler2_mobile numeric(14,0),
@handler2_landline numeric(18,0),
@handler2_email varchar(50),
@handler3_name varchar(50),
@handler3_mobile numeric(14,0),
@handler3_landline numeric(18,0),
@handler3_email varchar(50),
@connection_type_id int,
@connection_size_id int,
@connection_plan_id int,
@connection_start_wish date

all the data type is same in sqltable as above…

and this is my «aspx.cs» code…

protected void btn_submit_Click(object sender, EventArgs e)
    {
        string owner_birthdate,wish_start_from,ac_code_id;
        owner_birthdate = ddl_owner_dob_mm.Text + '/' + ddl_owner_dob_dd.Text + '/' + ddl_owner_dob_yyyy.Text;
        wish_start_from=ddl_conn_wish_mm.Text+'/'+ddl_conn_wish_dd.Text+'/'+ddl_conn_wish_yyyy.Text;

        if (rbl_conn_for.SelectedValue == "1")
        {
            string hp="HP";

            conn.Open();
            SqlCommand cmd = new SqlCommand("insert_into_reg_housing_plot",conn);
            cmd.CommandType = CommandType.StoredProcedure;


            SqlParameter prm_datetime = new SqlParameter(lbl_date_time.Text, "@registration_datetime");
            cmd.Parameters.Add(prm_datetime);

            SqlParameter prm_owner_surname = new SqlParameter("@owner_surname", txt_owner_surname.Text);
            cmd.Parameters.Add(prm_owner_surname);

            SqlParameter prm_owner_first_name = new SqlParameter("@owner_first_name", txt_owner_first_name.Text);
            cmd.Parameters.Add(prm_owner_first_name);

            SqlParameter prm_owner_middle_name = new SqlParameter("@owner_middle_name", txt_owner_middle_name.Text);
            cmd.Parameters.Add(prm_owner_middle_name);

            SqlParameter prm_owner_DOB = new SqlParameter("@owner_DOB", owner_birthdate);
            cmd.Parameters.Add(prm_owner_DOB);

            SqlParameter prm_add_housing_plot = new SqlParameter("@add_of_housing_plot", txt_address_housing_plot.Text);
            cmd.Parameters.Add(prm_add_housing_plot);

            SqlParameter prm_handler1_name = new SqlParameter("@handler1_name", txt_handler1_name.Text);
            cmd.Parameters.Add(prm_handler1_name);

            SqlParameter prm_handler1_mobile = new SqlParameter("@handler1_mobile", txt_handler1_mobile.Text);
            cmd.Parameters.Add(prm_handler1_mobile);

            SqlParameter prm_handler1_landline = new SqlParameter("@handler1_landline", txt_handler1_landline.Text);
            cmd.Parameters.Add(prm_handler1_landline);

            SqlParameter prm_handler1_email = new SqlParameter("@handler1_email", txt_handler1_email.Text);
            cmd.Parameters.Add(prm_handler1_email);

            SqlParameter prm_handler2_name = new SqlParameter("@handler2_name", txt_handler2_name.Text);
            cmd.Parameters.Add(prm_handler2_name);

            SqlParameter prm_handler2_mobile = new SqlParameter("@handler2_mobile", txt_handler2_mobile.Text);
            cmd.Parameters.Add(prm_handler2_mobile);

            SqlParameter prm_handler2_landline = new SqlParameter("@handler2_landline", txt_handler2_landline.Text);
            cmd.Parameters.Add(prm_handler2_landline);

            SqlParameter prm_handler2_email = new SqlParameter("@handler2_email", txt_handler2_email.Text);
            cmd.Parameters.Add(prm_handler2_email);

            SqlParameter prm_handler3_name = new SqlParameter("@handler3_name", txt_handler3_name.Text);
            cmd.Parameters.Add(prm_handler3_name);

            SqlParameter prm_handler3_mobile = new SqlParameter("@handler3_mobile", txt_handler3_mobile.Text);
            cmd.Parameters.Add(prm_handler3_mobile);

            SqlParameter prm_handler3_landline = new SqlParameter("@handler3_landline", txt_handler3_landline.Text);
            cmd.Parameters.Add(prm_handler3_landline);

            SqlParameter prm_handler3_email = new SqlParameter("@handler3_email", txt_handler3_email.Text);
            cmd.Parameters.Add(prm_handler3_email);

            if (rbl_connection_type.SelectedValue == "3")
            {
                SqlParameter prm_yearly_conn_type = new SqlParameter("@connection_type_id",rbl_connection_type.SelectedValue);
                cmd.Parameters.Add(prm_yearly_conn_type);

                SqlParameter prm_fix_yearly_size = new SqlParameter("@connection_size_id",ddl_conn_size_selection_for_fixed_yearly_plan.SelectedValue);
                cmd.Parameters.Add(prm_fix_yearly_size);

                SqlParameter prm_fix_yearly_plan = new SqlParameter("@connection_plan_id", ddl_plan_selection_for_fixed_yearly_conn.SelectedValue);
                cmd.Parameters.Add(prm_fix_yearly_plan);
            }
            else if (rbl_connection_type.SelectedValue == "1")
            {
                SqlParameter prm_monthly_conn_type = new SqlParameter("@connection_type_id", rbl_connection_type.SelectedValue);
                cmd.Parameters.Add(prm_monthly_conn_type);

                SqlParameter prm_fix_monthly_size = new SqlParameter("@connection_size_id", ddl_conn_size_selection_for_fixed_plant.SelectedValue);
                cmd.Parameters.Add(prm_fix_monthly_size);

                SqlParameter prm_fix_monthly_plan = new SqlParameter("@connection_plan_id", ddl_plan_selection_for_fixed_conn.SelectedValue);
                cmd.Parameters.Add(prm_fix_monthly_plan);
            }
            else if (rbl_connection_type.SelectedValue == "2")
            {
                SqlParameter prm_monthly_conn_type = new SqlParameter("@connection_type_id", rbl_connection_type.SelectedValue);
                cmd.Parameters.Add(prm_monthly_conn_type);

                SqlParameter prm_fix_monthly_plan = new SqlParameter("@connection_plan_id", ddl_conn_size_for_meter_plan.SelectedValue);
                cmd.Parameters.Add(prm_fix_monthly_plan);
            }

            SqlParameter prm_start_wish = new SqlParameter("@connection_start_wish",wish_start_from);
            cmd.Parameters.Add(prm_start_wish);


            SqlCommand ac = new SqlCommand("select max(ac_code_int) from registration_for_housing_plot",conn);
            object a;
            a=ac.ExecuteScalar();
            if (a.ToString() == "")
        {
            a="1001";
             ac_code_id= hp + a;
        }
        else
        {
            Int64 v;
            v = (Int64.Parse(a.ToString())) + 1;
            ac_code_id = hp + v.ToString();
            
           
        }
        
        SqlParameter prm_ac_code_id = new SqlParameter("@ac_code_id", ac_code_id);
        cmd.Parameters.Add(prm_ac_code_id);

        ac.ExecuteNonQuery();

        SqlParameter prm_ac_code_password = new SqlParameter("@ac_password",txt_confirm_password.Text);
        cmd.Parameters.Add(prm_ac_code_password);

        cmd.ExecuteNonQuery();
            conn.Close();
        }
        else if (rbl_conn_for.SelectedValue == "2")
        {
            string ci = "CI";

            conn.Open();
            SqlCommand cmd = new SqlCommand("insert_into_reg_c_industry", conn);
            cmd.CommandType = CommandType.StoredProcedure;


            SqlParameter prm_datetime = new SqlParameter("@registration_datetime", lbl_date_time.Text);
            cmd.Parameters.Add(prm_datetime);

            SqlParameter prm_owner_surname = new SqlParameter("@owner_surname", txt_owner_surname.Text);
            cmd.Parameters.Add(prm_owner_surname);

            SqlParameter prm_owner_first_name = new SqlParameter("@owner_first_name", txt_owner_first_name.Text);
            cmd.Parameters.Add(prm_owner_first_name);

            SqlParameter prm_owner_middle_name = new SqlParameter("@owner_middle_name", txt_owner_middle_name.Text);
            cmd.Parameters.Add(prm_owner_middle_name);

            SqlParameter prm_owner_DOB = new SqlParameter("@owner_DOB", owner_birthdate);
            cmd.Parameters.Add(prm_owner_DOB);

            SqlParameter prm_add_c_industry = new SqlParameter("@add_of_c_industry", txt_address_commercial_industry.Text);
            cmd.Parameters.Add(prm_add_c_industry);

            SqlParameter prm_handler1_name = new SqlParameter("@handler1_name", txt_handler1_name.Text);
            cmd.Parameters.Add(prm_handler1_name);

            SqlParameter prm_handler1_mobile = new SqlParameter("@handler1_mobile", txt_handler1_mobile.Text);
            cmd.Parameters.Add(prm_handler1_mobile);

            SqlParameter prm_handler1_landline = new SqlParameter("@handler1_landline", txt_handler1_landline.Text);
            cmd.Parameters.Add(prm_handler1_landline);

            SqlParameter prm_handler1_email = new SqlParameter("@handler1_email", txt_handler1_email.Text);
            cmd.Parameters.Add(prm_handler1_email);

            SqlParameter prm_handler2_name = new SqlParameter("@handler2_name", txt_handler2_name.Text);
            cmd.Parameters.Add(prm_handler2_name);

            SqlParameter prm_handler2_mobile = new SqlParameter("@handler2_mobile", txt_handler2_mobile.Text);
            cmd.Parameters.Add(prm_handler2_mobile);

            SqlParameter prm_handler2_landline = new SqlParameter("@handler2_landline", txt_handler2_landline.Text);
            cmd.Parameters.Add(prm_handler2_landline);

            SqlParameter prm_handler2_email = new SqlParameter("@handler2_email", txt_handler2_email.Text);
            cmd.Parameters.Add(prm_handler2_email);

            SqlParameter prm_handler3_name = new SqlParameter("@handler3_name", txt_handler3_name.Text);
            cmd.Parameters.Add(prm_handler3_name);

            SqlParameter prm_handler3_mobile = new SqlParameter("@handler3_mobile", txt_handler3_mobile.Text);
            cmd.Parameters.Add(prm_handler3_mobile);

            SqlParameter prm_handler3_landline = new SqlParameter("@handler3_landline", txt_handler3_landline.Text);
            cmd.Parameters.Add(prm_handler3_landline);

            SqlParameter prm_handler3_email = new SqlParameter("@handler3_email", txt_handler3_email.Text);
            cmd.Parameters.Add(prm_handler3_email);

            if (rbl_connection_type.SelectedValue == "3")
            {
                SqlParameter prm_yearly_conn_type = new SqlParameter("@connection_type_id", rbl_connection_type.SelectedValue);
                cmd.Parameters.Add(prm_yearly_conn_type);

                SqlParameter prm_fix_yearly_size = new SqlParameter("@connection_size_id", ddl_conn_size_selection_for_fixed_yearly_plan.SelectedValue);
                cmd.Parameters.Add(prm_fix_yearly_size);

                SqlParameter prm_fix_yearly_plan = new SqlParameter("@connection_plan_id", ddl_plan_selection_for_fixed_yearly_conn.SelectedValue);
                cmd.Parameters.Add(prm_fix_yearly_plan);
            }
            else if (rbl_connection_type.SelectedValue == "1")
            {
                SqlParameter prm_monthly_conn_type = new SqlParameter("@connection_type_id", rbl_connection_type.SelectedValue);
                cmd.Parameters.Add(prm_monthly_conn_type);

                SqlParameter prm_fix_monthly_size = new SqlParameter("@connection_size_id", ddl_conn_size_selection_for_fixed_plant.SelectedValue);
                cmd.Parameters.Add(prm_fix_monthly_size);

                SqlParameter prm_fix_monthly_plan = new SqlParameter("@connection_plan_id", ddl_plan_selection_for_fixed_conn.SelectedValue);
                cmd.Parameters.Add(prm_fix_monthly_plan);
            }
            else if (rbl_connection_type.SelectedValue == "2")
            {
                SqlParameter prm_monthly_conn_type = new SqlParameter("@connection_type_id", rbl_connection_type.SelectedValue);
                cmd.Parameters.Add(prm_monthly_conn_type);

                SqlParameter prm_fix_monthly_plan = new SqlParameter("@connection_plan_id", ddl_conn_size_for_meter_plan.SelectedValue);
                cmd.Parameters.Add(prm_fix_monthly_plan);
            }

            SqlParameter prm_start_wish = new SqlParameter("@connection_start_wish", wish_start_from);
            cmd.Parameters.Add(prm_start_wish);


            SqlCommand ac = new SqlCommand("select max(ac_code_int) from registration_for_comercial_industry",conn);
            object a;
            a = ac.ExecuteScalar();
            if (a.ToString() == "")
            {
                a = "1001";
                ac_code_id = ci + a;
            }
            else
            {
                Int64 v;
                v = (Int64.Parse(a.ToString())) + 1;
                ac_code_id = ci + v.ToString();


            }
            
            SqlParameter prm_ac_code_id = new SqlParameter("@ac_code_id", ac_code_id);
            cmd.Parameters.Add(prm_ac_code_id);

            ac.ExecuteNonQuery();

            SqlParameter prm_ac_code_password = new SqlParameter("@ac_password", txt_confirm_password.Text);
            cmd.Parameters.Add(prm_ac_code_password);

            cmd.ExecuteNonQuery();
            conn.Close();
        }
    }

plzz help me solve this…
thanks a lot in advance… :)

Понравилась статья? Поделить с друзьями:
  • Ошибка при проверке сертификата c отпечатком пфр
  • Ошибка при преобразовании типа данных nvarchar к float
  • Ошибка при проверке свободных блоков на носителе ultraiso
  • Ошибка при предоставлении общего доступа общий ресурс не создан
  • Ошибка при проверке пользователя ртс тендер 223 фз