Arithmetic overflow error converting nvarchar to data type numeric

Arithmetic overflow error converting nvarchar to data type numeric. Forum – Learn more on SQLServerCentral

October 13, 2012 at 10:58 am

#265630

hello

when i run the following sql query:

«update table set price = price * 1.1 «

i get the following error :

«Msg 8115, Level 16, State 8, Line 1

Arithmetic overflow error converting nvarchar to data type numeric.

The statement has been terminated.»

the table is set to nvarchar, and i am just trying to make the prices go up 10%

any ideas?

thanks!

Gopi S

Ten Centuries

Points: 1091

Hi,

In the expression [price * 1.1], SQL Server tries to implicit convert price into numeric(2,1) because 1.1 is type numeric(2,1) which has higher precedence than nvarchar. I think your table should have values greater that 10.

say 10.1, 10.2…… where the precision value is exceeding 2.

To resolve this try

update table set price = price * cast(1.1 as numeric(10,4))

Note: If your price still has more that 10 precision value then change it accordingly.

Thanks

Gopi

duro654321

Mr or Mrs. 500

Points: 572

the value of the price field is:

.05

.25

.6

1

1.25

150.7

250

265.75

etc

so if there are no items price that are greater than $1000 then i would use the following: ?

update field set price = price * cast(1.1 as numeric(1000,7))

Gopi S

Ten Centuries

Points: 1091

no. ‘1000’ is precision 4. so you can have numeric(4,0). ie 4 decimal values in the left of decimal point and not numeric(1000,7)

Ref: http://msdn.microsoft.com/en-us/library/ms187746.aspx

You can understand what is numeric data type and what is precision and scale number

duro654321

Mr or Mrs. 500

Points: 572

i ran «update table set price = price * cast(1.1 as numeric(10,4))» and that worked pretty well

thanks! 🙂

TomThomson

SSC Guru

Points: 104773

Gopi S (10/13/2012)


Hi,

In the expression [price * 1.1], SQL Server tries to implicit convert price into numeric(2,1) because 1.1 is type numeric(2,1) which has higher precedence than nvarchar. I think your table should have values greater that 10.

say 10.1, 10.2…… where the precision value is exceeding 2.

To resolve this try

update table set price = price * cast(1.1 as numeric(10,4))

Note: If your price still has more that 10 precision value then change it accordingly.

Thanks

Gopi

Yes, it’s the implicit conversion that’s going wrong because the default type for 1.2 is numeric(2,1). But there’s another problem: if you try to increase a price like 10.37 by 10%, just multiplying by 1.1 doesn’t work because it will deliver 11.387 which may not be a valid currency amount (eg if the currency is euro the smallest value is .01, so .007 is invalid) and you have to decide what rounding you want to do in this case — perhaps rounding to nearest valid number (and what ever you want to do to round something ending in .xy5) or perhaps rounding down or perhaps some other rule.

So I think I would go for something like

update table

set price = convert(nvarchar(36), cast(cast(price as numeric(35,2))*1.1 as numeric(35,2)))

(the inner cast should solve the error; the outer cast does simple default rounding, so replace it with something that does whatever sort or rounding you need if the default isn’t what you want)

Of course if you have a currency unit that splits into 1000 parts instead of 100, you need to use scale 3 instead of scale 2, and so on for other splits. If you will sometimes want to multiply by something more complicated than 1.1 (for example by 1.0625, for a 6¼% increase) you need to reduce the precision from 35 to avoid the possibility of the multiply operation doing some rounding instead of whatever rounding you have chosen to do — pushing it down to 32 isn’t going to put much of a constraint on your prices, unless you have prices of 1000000000000000000000000000000.00 currency units or more. In fact you could just look and see what your nvarchar price column is declared as: if it’s nvarchar(N) you should use precision N-1, unless whoever specified it was being sloppy.

Tom

duro654321

Mr or Mrs. 500

Points: 572

thank you!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

that worked, it cleaned up the data from 5.50000000 to 5.5

but now when i run «select top 10 * from table order by price «

it shows me

x 9.9

x 9.9

instead of 10 +

??

any ideas?

duro654321

Mr or Mrs. 500

Points: 572

when i run

select * from table order by price asc

i get…

115.50

36.00

4.95

4.95

4.95

47.30

49.50

49.50

53.90

when i should get

4.95

4.95

4.95

36.00

47.30

49.50

49.50

53.90

115.50

what do i need to change in the sql query ?

Gopi S

Ten Centuries

Points: 1091

You are trying to order the varchar column and not numeric though the value looks numeric.

Try

—Query 1

select

price

from table

order by CAST(price as numeric(10,4)) asc

—Query 2

select price from (

select CAST(price as numeric(10,4))

price

from table) T

order by price asc

Again this is just hint. Your cast function should have appropriate precision and scale based on previous post

Sean Lange

SSC Guru

Points: 286562

Or even better, change the column type so you don’t have to continually fight the fact that you are storing numbers in a character column.

Don Bernstein

Old Hand

Points: 393

Thanks for this post — it helped me solve a similar problem.

But, wouldn’t it be more clear to use:

update table set price = cast(price as numeric(10,4)) * 1.1

Содержание

  1. Arithmetic overflow error converting nvarchar to data type numeric.
  2. Ошибка SQL: Arithmetic overflow error converting numeric to data type numeric
  3. Специальные предложения
  4. См. также
  5. Реструктуризация базы в 1С: для чего требуется и о назначении в целом
  6. Копии баз данных и размер БД. Проблемы и пути решения
  7. Работа с файлом *.dt формата
  8. Регистрация в центре лицензирования не выполнена
  9. Настройка отказоустойчивого кластера 1C + PostgreSQL (etcd+patroni+haproxy) на Centos 8
  10. Workaround me в 1С/MS SQL и не только, системный подход к созданию костылей
  11. Ошибка Dump в 1С
  12. Режимы запуска системы 1С:Предприятие
  13. Оптимизация высоконагруженных конфигураций: история маленькой победы, или советы тем, кто столкнулся с проблемой впервые и не знает, что делать
  14. Ошибка формата потока расширения
  15. Пропадающие файлы на томе в 1С: КА 2.5
  16. Ошибка загрузки большого архива 1Cv8.dt в PostgresSQL на платформе 1С 8.3.19
  17. SAMBA для 1С
  18. Регламентное задание по завершению сеансов пользователей 1С
  19. Базовые приемы работы с кластером 1С при помощи БСП

Arithmetic overflow error converting nvarchar to data type numeric.

October 13, 2012 at 10:58 am

when i run the following sql query:

«update table set price = price * 1.1 «

i get the following error :

«Msg 8115, Level 16, State 8, Line 1

Arithmetic overflow error converting nvarchar to data type numeric.

The statement has been terminated.»

the table is set to nvarchar, and i am just trying to make the prices go up 10%

October 13, 2012 at 12:01 pm

In the expression [price * 1.1], SQL Server tries to implicit convert price into numeric(2,1) because 1.1 is type numeric(2,1) which has higher precedence than nvarchar. I think your table should have values greater that 10.

say 10.1, 10.2. where the precision value is exceeding 2.

To resolve this try

update table set price = price * cast(1.1 as numeric(10,4))

Note: If your price still has more that 10 precision value then change it accordingly.

October 13, 2012 at 12:27 pm

the value of the price field is:

so if there are no items price that are greater than $1000 then i would use the following: ?

update field set price = price * cast(1.1 as numeric(1000,7))

October 13, 2012 at 12:39 pm

no. ‘1000’ is precision 4. so you can have numeric(4,0). ie 4 decimal values in the left of decimal point and not numeric(1000,7)

You can understand what is numeric data type and what is precision and scale number

October 13, 2012 at 12:51 pm

i ran «update table set price = price * cast(1.1 as numeric(10,4))» and that worked pretty well

October 13, 2012 at 1:20 pm

In the expression [price * 1.1], SQL Server tries to implicit convert price into numeric(2,1) because 1.1 is type numeric(2,1) which has higher precedence than nvarchar. I think your table should have values greater that 10.

say 10.1, 10.2. where the precision value is exceeding 2.

To resolve this try

update table set price = price * cast(1.1 as numeric(10,4))

Note: If your price still has more that 10 precision value then change it accordingly.

Yes, it’s the implicit conversion that’s going wrong because the default type for 1.2 is numeric(2,1). But there’s another problem: if you try to increase a price like 10.37 by 10%, just multiplying by 1.1 doesn’t work because it will deliver 11.387 which may not be a valid currency amount (eg if the currency is euro the smallest value is .01, so .007 is invalid) and you have to decide what rounding you want to do in this case — perhaps rounding to nearest valid number (and what ever you want to do to round something ending in .xy5) or perhaps rounding down or perhaps some other rule.

So I think I would go for something like

set price = convert(nvarchar(36), cast(cast(price as numeric(35,2))*1.1 as numeric(35,2)))

(the inner cast should solve the error; the outer cast does simple default rounding, so replace it with something that does whatever sort or rounding you need if the default isn’t what you want)

Of course if you have a currency unit that splits into 1000 parts instead of 100, you need to use scale 3 instead of scale 2, and so on for other splits. If you will sometimes want to multiply by something more complicated than 1.1 (for example by 1.0625, for a 6¼% increase) you need to reduce the precision from 35 to avoid the possibility of the multiply operation doing some rounding instead of whatever rounding you have chosen to do — pushing it down to 32 isn’t going to put much of a constraint on your prices, unless you have prices of 1000000000000000000000000000000.00 currency units or more. In fact you could just look and see what your nvarchar price column is declared as: if it’s nvarchar(N) you should use precision N-1, unless whoever specified it was being sloppy.

Источник

Ошибка SQL: Arithmetic overflow error converting numeric to data type numeric

По запросу «Arithmetic overflow error converting numeric to data type numeric» есть куча обсуждений и очень мало записано решений. Мой случай, вероятно, частный, но кого-то подтолкнет в направлении «куда копать».

SQL 2016 Standard
Платформа 8.3.18

При выполнении запросов к БД типа:

Когда, количество строк >

10 000 000, выдавалась ошибка:

Решение

Добавлено преобразование типа Число к конкретной длине. Баг перестал воспроизводиться.

Коллеги, если сталкивались с ошибкой, в комментариях опишите причину сбоя, и, если знают — другие способы устранения.

Специальные предложения

int до 2 147 483 647, не думаю, что такое кол-во записей в регистре.

Скорее всего, это игры 1С/MSSQL с precison numeric. Например, рассматривает 1 как Numeric(7,0), пытаясь к нему преобразовать результат СУММА(1).

P.S.
В конкретном примере использование «Сумма», по-моему, неоправдано, ибо Количество(*), скорее-всего выполнится верно.
( а если есть еще индекс по одному из измерений и делать COUNT(OUR_FIELD), то и full index scan не так страшен).

Советы по использованию «Выразить», наверное, относятся к случаю, когда вместо литерала суммируют что-то более осмысленное.

Лезть в профайлер и смотреть во что 1С превращает 1, неохота.

Для подсчета кол-ва записей лучше юзать:
Выбрать Количество(1) Из РегистрНакопления.ТоварыКПоступлению

ну а если нужна сумма, то можно применить такой костыль:
Выбрать Сумма(0.001) Из РегистрНакопления.ТоварыКПоступлению
получите сумму в тысячах )

(4) мысль автора комментария по-моему осталась не законченной.
Заметил и что?
Если решил, то как?
Если знаете решение — почему не поделиться с сообществом?
Кто знает о вашем достижении?

Если по существу — то вы молодец.

(6) наверное, мой навык гугления не такой как ваш.
Видел эту статью.
Там SQL древний описан и я не стал ее читать (зря).

Ничего страшного, если решение будет записано еще раз с указанием более свежей версии SQL.

Обновление 25.08.21 11:18

См. также

Реструктуризация базы в 1С: для чего требуется и о назначении в целом

В статье расскажем о том, как в 1С:Управление торговлей происходит реструктуризация таблиц информационной базы и почему это требуется производить регулярно.

07.12.2022 1106 Koder_Line 4

Копии баз данных и размер БД. Проблемы и пути решения

Столкнулся с проблемой быстрого роста объема БД. Статья о том, как решал эту проблему.

30.11.2022 1070 DrMih 5

Работа с файлом *.dt формата

В статье расскажем о том, что такое *.dt формат, для чего он применяется, как создать *.dt файл, куда и как загружать*.dt файл, а также дадим некоторые советы по работе с *.dt файлами.

29.11.2022 1367 Koder_Line 5

Регистрация в центре лицензирования не выполнена

Каждый пользователь программ 1С сталкивался с ситуацией, когда при входе в программу 1С появляется всплывающая картинка с информацией, что «Регистрация конфигурации в центре лицензирования не выполнена», которая появляется и мешает нам работать. При этом такая ситуация может возникнуть в любой конфигурации 1С.

28.09.2022 1421 Koder_Line 2

Настройка отказоустойчивого кластера 1C + PostgreSQL (etcd+patroni+haproxy) на Centos 8

Настройка отказоустойчивого кластера PostgreSQL для сервера приложений 1С на операционной системе Centos 8.

22.08.2022 2638 user1332168 10

Workaround me в 1С/MS SQL и не только, системный подход к созданию костылей

Workaround свидетельствует о невозможности решить проблему «правильным путем» и вызывает чувство стыда. Но практика показывает, что способность решать проблемы через workaround является порой единственным способом решить проблему в разумное время. А победителей, как говорят, не судят, так почему бы не создавать workaround по системе?

15.08.2022 1081 1CUnlimited 0

Ошибка Dump в 1С

В данной статье будет рассмотрено представление ошибки Dump в 1С, будет проведена её диагностика, а также определено, как устранить данную ошибку и продолжить дальнейшую корректную работу системы 1С. Также будет представлена общая информация об ошибке Memorydump, для более глубокого её понимания.

15.07.2022 1431 Koder_Line 3

Режимы запуска системы 1С:Предприятие

Существует несколько путей установки режимов запуска 1С:Предприятие. Рассмотрим запуски системы в режиме «1С:Предприятие» и в режиме Конфигуратора. Проговорим предварительно, что одновременное использование нескольких режимов не допускается для того, чтобы указать параметры командной строки.

12.07.2022 1813 Koder_Line 1

Оптимизация высоконагруженных конфигураций: история маленькой победы, или советы тем, кто столкнулся с проблемой впервые и не знает, что делать

Пост будет больше интересен руководителям отделов ИТ сопровождения или проектным менеджерам, перед которыми будет стоять задача решения проблемы деградации производительности баз данных 1С. Пост для тех, кому эта тема нова, нет особого опыта, и с ходу непонятно, с чего начать.

24.05.2022 3702 avolsed 15

Ошибка формата потока расширения

Восстановление базы данных 1С с ошибкой «Ошибка формата потока» с «полетевшим» расширением, когда все остальные методы уже испробованы.

19.05.2022 1244 yupi71 9

Пропадающие файлы на томе в 1С: КА 2.5

На протяжении месяца пропадали файлы: прикрепленные изображения, документы в ЭДО. КА 2.5, актуальная редакция на поддержке. Этого не описано НИГДЕ и если бы я нашел такую тему, у меня мы было гораздо меньше проблем.

05.04.2022 1177 mlashko 4

Ошибка загрузки большого архива 1Cv8.dt в PostgresSQL на платформе 1С 8.3.19

1С для платформы 8.3.19 ускорили загрузку dt-файлов за счет разбивки на несколько фоновых заданий. В итоге словили ошибку блокировки при загрузке в СУБД PostgresSQL большого 1cv8.dt-файла размером 25 Gb «ERROR: canceling statement due to lock timeout». Напишу, как в итоге загрузили этот dt-файл.

30.01.2022 8096 sapervodichka 51

SAMBA для 1С

Представлен необходимый минимум настройки SAMBA для работы файловых баз 1С через общий ресурс.

24.12.2021 4291 compil7 6

Регламентное задание по завершению сеансов пользователей 1С

Завершить работу пользователей в 1С ночью. Регламентное завершение работы.

06.12.2021 2448 Swamt 20

Базовые приемы работы с кластером 1С при помощи БСП

В данной публикации я рассматриваю базовые приемы работы с кластером серверных баз 1С, используя типовые типовые возможности библиотеки стандартных подсистем (БСП).

Источник

This error comes when you try to store an out-of-range floating point value into a numeric variable. For example, if your NUMERIC or DECIMAL variable is defined as NUMERIC(5,2) then the maximum value it can hold is 999.99, if you try to store something like 1000.00 then it will throw «Arithmetic overflow error converting numeric to data type numeric». One of the common reasons for this error is the ignorance and misunderstanding of the NUMERIC data type. For example, many SQL Server DBAs and developers think that a NUMERIC(5,2) variable can hold a 7 digit floating point number where 5 digits are before the decimal and 2 digits are after the decimal. This is wrong.

A NUMERIC(5,2) means, the total number of digits in the value cannot exceed 5 and decimal precision is 2 digits i.e. the maximum possible value is 999.99.

Another thing SQL programmers don’t know and remember about NUMERIC or DECIMAL data types in Microsoft SQL Server is that it doesn’t throw this error if you specify more digits than permitted after the decimal point, instead, it does rounding for example if you store 100.999 then it will store 101.00 after rounding.

Here is an SQL query to prove these points:

DECLARE @sample NUMERIC(5,2)
SET @sample = 1000.554
SELECT @sample

Output
Arithmetic overflow error converting numeric to data type numeric.

Explanation: 

This time SQL Server throws the error because we are trying to store 1000 but the maximum value a NUMERIC(5,2) can hold is 999 before the decimal point. You need to increase the width of the variable to store this number e.g. making @sample NUMERIC(6,2) will solve this error as shown below.

By the way, if you are new to Microsoft SQL Server and T-SQL then I also suggest you join a comprehensive course to learn SQL Server fundamentals and how to work with T-SQL. If you need a recommendation then I suggest you go through the Microsoft SQL for Beginners online course by Brewster Knowlton on Udemy. It’s a great course to start with T-SQL and SQL queries in SQL Server.

Arithmetic overflow error converting numeric to data type numeric in SQL Server

Arithmetic overflow error converting numeric to data type numeric in SQL Server Examples

Here are some more SQL queries which will confirm the behavior of the NUMERIC variable and its range:

DECLARE @sample NUMERIC(5,2)
SET @sample = 100.554 // no rounding because the extra digit is less than 5
SELECT @sample AS Result

Result
100.55

DECLARE @sample NUMERIC(5,2)
SET @sample = 100.555 // rounding will happen
SELECT @sample AS Result

Result
100.56


DECLARE @sample NUMERIC(5,2)
SET @sample = 100.55 // no rounding because value is under defined precision
SELECT @sample AS Result

Result
100.55


DECLARE @sample NUMERIC(5,2)
SET @sample = 100.999 // Rounding to nearest value
SELECT @sample AS Result

Result
101.00

DECLARE @sample NUMERIC(5,2)
SET @sample = 999.999 // error because after rounding value will be
                      // out-of-range for defined numeric type
SELECT @sample AS Result

Result
Arithmetic overflow error converting numeric to data type numeric.

That’s all about «Arithmetic overflow error converting numeric to data type numeric in SQL Server». You can see that cause of the error is usually out-of-range value for the defined NUMERIC type. Just check the source of value and correct or increase the precision level of your column.

Always remember that NUMERIC(5,2) means a total of 5 digits with 2 digits after the decimal point, and the maximum value it can hold is 999.99. Beware of rounding due to more additional digits after the decimal point, which can also cause «Arithmetic overflow error converting numeric to data type numeric» in Microsoft SQL Server.

Related SQL Server articles you may like to explore

  • Difference between rank(), row_number(), and dense_rank() in SQL? (answer)
  • How to replace NULL with empty String in SQL Server? (tutorial)
  • Difference between Cast, Convert, and Parse method in SQL? (answer)
  • Difference between coalesce() and isNull() in Microsoft SQL Server? (answer)
  • How to remove duplicate rows from a table in SQL? (solution)
  • How to create an Identity column in SQL Server? (example)
  • How to format Date in Microsoft SQL Server? (example)
  • 5 Web sites to learn SQL online for FREE? (resource)
  • How to find the length of a string in SQL Server? (example)
  • How to convert the result of a SELECT command into a CSV String? (example)
  • The right way to check for NULL values in the SQL query? (example)
  • How to split String in SQL Server? (answer)
  • What is the difference between close and deallocate a cursor? (answer)
  • How to find all customers who have never ordered? (solution)
  • The right way to compare dates in SQL query? (example)
  • How to add columns into an existing table in MSSQL? (example)

Thanks for reading this article. If you like the information given here and my explanation then please share it with your friends and colleagues. 

Not sure what I’m doing wrong here, but I keep getting the following error despite trying several approaches (apart from using a seed, but I’d like to keep my inserts in the migration):

  [PDOException]
  SQLSTATE[22003]: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]Arithmetic overflow error converting nvarchar to data type numeric.

My up() method looks as follows:

        // options for escalation index additional columns
        $rateOptions = array(
            'scale'     => 13,
            'precision' => 13,
        );

        // drop current table
        $this->dropTable('ams_escalation_index');

        // retrieve and empty table
        $table = $this->table('ams_escalation_index', array(
            'id'    => 'escalation_index_id',
        ));

        // add new columns and update table structure
        $table->addColumn('escalation_month',   'integer');
        $table->addColumn('escalation_year',    'integer');
        $table->addColumn('escalation_index',   'decimal', $rateOptions);
        $table->addColumn('labour',             'decimal',  $rateOptions);
        $table->addColumn('plant',              'decimal',  $rateOptions);
        $table->addColumn('materials',          'decimal',  $rateOptions);
        $table->addColumn('fuel',               'decimal',  $rateOptions);
        $table->create();

        // add table data
        global $Paths;
        $fh = fopen(dirname(__FILE__) . '/escalation_index_migration/escalation_indexes.csv', 'r');
        // csv field order
        $fields = array(
            'escalation_month',
            'escalation_year',
            'labour',
            'plant',
            'materials',
            'fuel',
            'escalation_index',
        );
        $i = 1;
        while ( $row = fgetcsv($fh) ) {

            // convert row values to nominal values
            $row[0] = intval(date('n', strtotime($row[0])));
            $row[1] = intval($row[1]);
            $row[2] = floatval($row[2]);
            $row[3] = floatval($row[3]);
            $row[4] = floatval($row[4]);
            $row[5] = floatval($row[5]);
            $row[6] = floatval($row[6]);

            // prepare data and insert
            $data = array_combine($fields, $row);
            $data['escalation_index_id'] = $i;
            $table->insert(array_combine($fields, $row));
            $i++;
        }
        $table->save();

Avatar of theartha

theartha

Flag for United States of America asked on 4/25/2011

INSERT INTO B
(
LastUpdated,
LastUpdatedBy
)
SELECT
TIMESTAMP,
‘TEST’
FROM A

I am trying to insert into B from A. I got the following error message.

Msg 8115, Level 16, State 8, Line 1
Arithmetic overflow error converting nvarchar to data type numeric.
The statement has been terminated.

DataTypes:

Table.B

lastUpdated : nvarchar(27)

Table.A

TimeStamp: DateTime

I am using SQL Server 2005

Please advice.

Thanks.

JavaMicrosoft SQL Server 2005

Avatar of undefined

INSERT INTO B
(
LastUpdated,
LastUpdatedBy
)
SELECT
convert(varchar,TIMESTAMP,121) as ]TimeStamp],
‘TEST’
FROM A

oops, you may want to convert(nvarchar instead of just varchar.  In theory either would work though.

also I got my bracket turned around, should be:

    as [TimeStamp]

actually, the alias is not really needed, so:

INSERT INTO B
(
LastUpdated,
LastUpdatedBy
)
SELECT
convert(nvarchar,TIMESTAMP,121),
‘TEST’
FROM A

@KnightEknight:

I am trying this query

INSERT INTO B
(
LastUpdated,
LastUpdatedBy
)
SELECT
ltrim(rtrim(convert(nvarchar,TIMESTAMP,121))),
‘TEST’
FROM A

Still same error.

INSERT INTO B
(
LastUpdated,
LastUpdatedBy
)
SELECT
convert(nvarchar,TIMESTAMP,121),
‘TEST’
FROM A

Still same error.

sorry, try this:

INSERT INTO B
(
LastUpdated,
LastUpdatedBy
)
SELECT
ltrim(rtrim(convert(nvarchar,cast([TIMESTAMP] as datetime,121))),
‘TEST’
FROM A

grr!  I think I left out a closing paren around the cast function — should be:

ltrim(rtrim(convert(nvarchar,cast([TIMESTAMP] as datetime),121))),

I got Incorrect syntax near ‘,’.

@ line…ltrim(rtrim(convert(nvarchar,cast([TIMESTAMP] as datetime,121))),

ltrim(rtrim(convert(nvarchar,cast([TIMESTAMP] as datetime),121))),

Arithmetic overflow error converting expression to data type datetime.
The statement has been terminated.

hmm, now that works for me.  Try this and tell me the result you get:

declare @ts timestamp
select  @ts = convert(timestamp,GETDATE())  — initialize @ts to a timestamp
select CONVERT(nvarchar,cast(@ts as datetime),121)

wow .. I got the results….
how to use this my query?

I mean, I got today’s date

results:

2011-04-25 14:29:01.223

TIMESTAMP is the name of your column, right?

… and it is also of type «timestamp» ?

typo error: my column is TransTimeStamp datatype nvarchar(27), my bad

I understood that you were not using the real table/column names, so no worries — I just wanted to make sure about the types.  The data type of TransTimeStamp on table B is nvarchar, but what is it on table A — timestamp or datetime?

or are you just trying to get the current date and time into B?

declare @ts TRANSTIMESTAMP
select  @ts = convert(TRANSTIMESTAMP,GETDATE())  — initialize @ts to a timestamp
select CONVERT(nvarchar,cast(@ts as datetime),121) from IMPORT_WMFUNT

Msg 2715, Level 16, State 3, Line 3
Column, parameter, or variable #1: Cannot find data type TRANSTIMESTAMP.
Parameter or variable ‘@ts’ has an invalid data type.

Yes, TIMESTAMP is a valid data type, as is DATETIME … I would expect TransTimeStamp to be your column name, but I need to know what its type is.

are you just trying to get the current date and time into B?  If so, then:

INSERT INTO B
(
LastUpdated,
LastUpdatedBy
)
SELECT
ltrim(rtrim(convert(nvarchar,getdate(),121))),
‘TEST’
FROM A

INSERT INTO B
(
LastUpdated,
LastUpdatedBy
)
SELECT
TransTimeStamp,
‘TEST’
FROM A

DataTypes:

Table.A

TransTimeStamp: nvarchar(27)

Table.B

lastUpdated : DateTime

INSERT INTO B
(
LastUpdated,
LastUpdatedBy
)
SELECT
convert(datetime,ltrim(rtrim(TransTimeStamp))),
‘TEST’
FROM A

now, the above assumes that TransTimeStamp has values in it that are properly formatted dates, like ’04/25/2011′ or ‘2011-04-25 03:14:01’

2010-10-18-09.34.14.000000 is nvarchar value in Table A.

I got the same error Arithmetic overflow error converting expression to data type datetime.
The statement has been terminated.

So I ran this query

select CONVERT(nvarchar,cast([TRANSTIMESTAMP] as datetime),121) from A

Still the same error

select convert(datetime,ltrim(rtrim(TransTimeStamp))) from A

same error

stand by, i got this now…

The date format of that column is non-standard, so first we have to transform it into a standard date, which is why this query is so ugly, but (hopefully) it will work:

INSERT INTO B
(
 LastUpdated,
 LastUpdatedBy
)
SELECT
convert(datetime,substring(TransTimeStamp,1,10)+’ ‘+substring(replace(TransTimeStamp,’.’,’:’),12,11)),
‘TEST’
FROM A

Still the same error:

so I ran

select convert(datetime,substring(TransTimeStamp,1,10)+’ ‘+substring(replace(TransTimeStamp,’.’,’:’),12,11))
 from A

Still same error.

okay, let’s break it down … run these separately:

select substring(TransTimeStamp,1,10)
from A

select substring(replace(TransTimeStamp,’.’,’:’),12,11)
from A

When I tried to convert the datatype, by right click and modify:

‘A’ table
— Warning: Data might be lost converting column ‘TransTimestamp’ from ‘nvarchar(27)’.

I clicked Yes

Got the following message

‘A’ table
— Unable to modify table.  
Arithmetic overflow error converting expression to data type datetime.
The statement has been terminated.

I don’t expect that will work anyway because the format of the text in that column is not a standardized date format.

Please post the results of the 2 queries above.

I mean these two:

select substring(TransTimeStamp,1,10)
from A

select substring(replace(TransTimeStamp,’.’,’:’),12,11)
from A

Query #1:

select substring(TransTimeStamp,1,10)
from A

Results:

 2010-10-1
 2010-10-1
 2010-10-1
 2010-10-1

Query #2:

select substring(replace(TransTimeStamp,’.’,’:’),12,11)
from A

Results:

-09:34:14:0
-09:34:29:0
-09:34:45:0
-09:35:02:0

Query #3:

select TransTimeStamp from A

Results:

 2010-10-18-09.34.14.000000
 2010-10-18-09.34.29.000000
 2010-10-18-09.34.45.000000
 2010-10-18-09.35.02.000000

well, it doesn’t look like that on my system, but maybe we can correct for it like this … please post the results:

select substring(TransTimeStamp,1,11)
from A

select substring(replace(TransTimeStamp,’.’,’:’),13,8)
from A

aha!  I see the problem — there is a leading space on those timestamps, correct?

… that’s why you were doing the ltrim / rtrim thing … let’s try this (only ltrim is necessary):

select substring(ltrim(TransTimeStamp),1,10)
from A

select substring(replace(ltrim(TransTimeStamp),’.’,’:’),12,11)
from A

— and if that works, then hopefully this will too:

INSERT INTO B
(
 LastUpdated,
 LastUpdatedBy
)
SELECT
convert(datetime,substring(ltrim(TransTimeStamp),1,10)+’ ‘+substring(replace(ltrim(TransTimeStamp),’.’,’:’),12,11)),
‘TEST’
FROM A

yes.

(Query 1)
select substring(TransTimeStamp,1,11)
from A
Results:
 2010-10-18
 2010-10-18
 2010-10-18
 2010-10-18

(Query 1)
select substring(replace(TransTimeStamp,’.’,’:’),13,8)
from A

Results
09:34:14:000000
09:34:29:000000
09:34:45:000000

Query 3

Results:
 2010-10-18-09.34.14.000000
 2010-10-18-09.34.29.000000
 2010-10-18-09.34.45.000000
 2010-10-18-09.35.02.000000

How about these?

select substring(ltrim(TransTimeStamp),1,10)
from A

select substring(replace(ltrim(TransTimeStamp),’.’,’:’),12,11)
from A

select substring(ltrim(TransTimeStamp),1,10)
from A

2010-10-18
2010-10-18
2010-10-18
2010-10-18

select substring(replace(ltrim(TransTimeStamp),’.’,’:’),12,11)
from A
09:34:14:00
09:34:29:00
09:34:45:00
09:35:02:00

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.

View this solution by signing up for a free trial.

Members can start a

7-Day free trial

and enjoy unlimited access to the platform.

WOW…you are amazing….finally it worked.

Thank you very much for the efforts. You made my day.

Thank you very much.

  • Remove From My Forums
  • Question

  • Hi

    I am having a strange issue selecting data from an indexed view… I am using SQL Server 2008 R2.

    I have created an indexed view with two columns — ‘DataValue’ and ‘EventFk’. ‘DataValue’ is nvarchar(max) and ‘EventFk’ is integer in the underlying tables.

    ‘DataValue’ holds call number details in the format ‘123456.0’, which I have converted to integer in the view, so that I can (a) index the view and (b) join this view to a table in another database, i.e.

    cast(cast(DataValue as decimal) as int) as ‘CallNo’

    I have successfully indexed the view, however I am having problems when it comes to actually selecting individual values from the view itself — for example:
    select * from dbo.vwMapToCLEOSSRSNEW where CallNo = 764266

    is returning the following error:
    Error converting data type nvarchar to numeric.

    However: select * from dbo.vwMapToCLEOSSRSNEW
    works perfectly.

    I am 99.9% certain that the view is not returning any nvarchar values, so I am uncertain as to why I would be receiving this error.  It’s as if my select statement is trying to retrieve the value 764266 from the views’ underlying tables (which DO contain
    nvarchar values), rather than the view itself.


    I have posted my full code below, any help is appreciated!

    Thanks

    —Create the view
    SET ANSI_NULLS ON
    GO

    SET QUOTED_IDENTIFIER ON
    GO

    CREATE VIEW [dbo].[vwMapToCLEOSSRSNEW] WITH SCHEMABINDING
    AS

    SELECT /*TOP 99 PERCENT*/ cast(cast(DataValue as decimal) as int) as ‘CallNo’,EventFk
    FROM dbo.[EventData] a
    INNER JOIN dbo.DataItem b ON a.EventDataId =b.EventDataFk
    WHERE b.[EventDataFK] = a.EventDataID
    AND DataKey = N’AuditCallRef’

    GO

    —create index
    create unique clustered index ucidx_CallNo_EventFk on dbo.vwMapToCLEOSSRSNEW(CallNo,EventFk)

Answers

  • Did you inspect the query plan to ensure that the view is actually being used?

    When you run a query against a view, SQL Server expands the view definition and the optimizes the expanded query. If you have Enterprise, Developer or Datacentre Edition, the optimization includes matching the query against indexed views. But just because
    there is an indexed view does not mean that the optimizer will use it for one reason or another. And if you are on Standard or Expression edition, the optimizer will not even try.

    However, there is a table hint you can apply, NOEXPAND as in:

    select * from dbo.vwMapToCLEOSSRSNEW WITH (NOEXPAND) where CallNo = 764266

    This hint prevents the expansion from happen, and since you seem to have created the view to work around this conversion problem, I suggest that you should always use the hint for this view, no matter which edition you have.


    Erland Sommarskog, SQL Server MVP, esquel@sommarskog.se

    • Proposed as answer by

      Saturday, May 7, 2011 6:13 PM

    • Marked as answer by
      Wolfmeister
      Monday, May 9, 2011 12:10 PM

I have a simple stored procedure where the target table and where clause condition are specified as parameters. The «Arithmetic overflow error converting nvarchar to data type numeric.» error is causing me a bit of frustration.

@TableName varchar(50), -- 'A_RECORD_ETH0' test value

@Time_ms decimal(18,4), -- '40388629085.6481' test value

@Records int out,       -- should result with '1' if test values are used

This works:

SELECT COUNT(*) as Count FROM A_RECORD_ETH0 WHERE Time_ms = 40388629085.6481

This works:

SET @sql = N'SET @Records = (SELECT COUNT(*) FROM A_RECORD_ETH0 WHERE Time_ms = 40388629085.6481 )'

EXEC sp_executesql @sql, N'@Records int output', @Records output

This works:

SET @sql = N'SET @Records = (SELECT COUNT(*) FROM '+ @TableName + ' WHERE Time_ms = 40388629085.6481 )'

EXEC sp_executesql @sql, N'@Records int output', @Records output

This results in the Arithmetic overflow error:

SET @sql = N'SET @Records = (SELECT COUNT(*) FROM '+ @TableName + ' WHERE Time_ms = ' + @Time_ms + ' )'

EXEC sp_executesql @sql, N'@Records int output', @Records output

This results in the Arithmetic overflow error even when cast is used:

SET @sql = N'SET @Records = (SELECT COUNT(*) FROM '+ @TableName + ' WHERE Time_ms = Cast ( ' + @Time_ms + ' as decimal(18,4)) )'

EXEC sp_executesql @sql, N'@Records int output', @Records output


Passing @Time_ms directly avoids the decimal->string->decimal conversion. It’s also more efficient; when @Time_ms changes, the server can still reuse the execution plan instead of generating a new one.

SET @sql = N'SET @Records = (SELECT COUNT(*) FROM '+ @TableName + ' WHERE Time_ms = @Time_ms'

EXEC sp_executesql @sql, N'@Time_ms decimal(18,4), @Records int output', @[email protected]_ms, @Records output

Понравилась статья? Поделить с друзьями:
  • Arithmetic overflow error converting expression to data type float
  • Arithmetic overflow error converting expression to data type datetime
  • Arithmetic overflow error converting expression to data type bigint
  • Arithmetic error java
  • Arithmetic error floating point overflow signalled